Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android技術精髓-Bitmap詳解

Android技術精髓-Bitmap詳解

編輯:關於Android編程

Android技術精髓-Bitmap詳解



Bitmap (android.graphics.Bitmap)

Bitmap是Android系統中的圖像處理的最重要類之一。用它可以獲取圖像文件信息,進行圖像剪切、旋轉、縮放等操作,並可以指定格式保存圖像文件。
Bitmap類:

public boolean compress (Bitmap.CompressFormat format, int quality, OutputStream stream) 壓縮:

將位圖的壓縮到指定的OutputStream。如果返回true,位圖可以通過傳遞一個相應的InputStream BitmapFactory.decodeStream(重建)。 format: 壓縮圖像的格式 quality: 0-100。 0含義壓縮為小尺寸,100壓縮的意思為最大質量。(PNG是無損的,會忽略品質設定 ) stream: OutputStream中寫入壓縮數據。 return: 是否成功壓縮到指定的流。

public void recycle()——回收位圖占用的內存空間,把位圖標記為Dead
public final boolean isRecycled() ——判斷位圖內存是否已釋放
public final int getWidth()——獲取位圖的寬度
public final int getHeight()——獲取位圖的高度
public final boolean isMutable()——圖片是否可修改
public int getScaledWidth(Canvas canvas)——獲取指定密度轉換後的圖像的寬度
public int getScaledHeight(Canvas canvas)——獲取指定密度轉換後的圖像的高度
public boolean compress(CompressFormat format, int quality, OutputStreamstream)——按指定的圖片格式以及畫質,將圖片轉換為輸出流。
format:Bitmap.CompressFormat.PNG或Bitmap.CompressFormat.JPEG
quality:畫質,0-100.0表示最低畫質壓縮,100以最高畫質壓縮。對於PNG等無損格式的圖片,會忽略此項設置。
常用的靜態方法:
public staticBitmap createBitmap(Bitmap src) ——以src為原圖生成不可變得新圖像 public staticBitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)——以src為原圖,創建新的圖像,指定新圖像的高寬以及是否變。 public staticBitmap createBitmap(int width, int height, Config config)——創建指定格式、大小的位圖 public staticBitmap createBitmap(Bitmap source, int x, int y, int width, int height)以source為原圖,創建新的圖片,指定起始坐標以及新圖像的高寬。 public staticBitmap createBitmap(Bitmap source, int x, int y, int width, int height, Matrixm, boolean filter)

BitmapFactory工廠類:
Option 參數類: public boolean inJustDecodeBounds——如果設置為true,不獲取圖片,不分配內存,但會返回圖片的高寬度信息。
public int inSampleSize——圖片縮放的倍數。如果設為4,則寬和高都為原來的1/4,則圖是原來的1/16。
public int outWidth——獲取圖片的寬度值
public int outHeight——獲取圖片的高度值
public int inDensity——用於位圖的像素壓縮比
public int inTargetDensity——用於目標位圖的像素壓縮比(要生成的位圖)
public boolean inScaled——設置為true時進行圖片壓縮,從inDensity到inTargetDensity。 讀取一個文件路徑得到一個位圖。如果指定文件為空或者不能解碼成文件,則返回NULL。
public staticBitmap decodeFile(String pathName, Options opts)
public staticBitmap decodeFile(String pathName) 讀取一個資源文件得到一個位圖。如果位圖數據不能被解碼,或者opts參數只請求大小信息時,則返回NuLL。(即當Options.inJustDecodeBounds=true,只請求圖片的大小信息。)
public staticBitmap decodeResource(Resources res, int id) public staticBitmap decodeResource(Resources res, int id, Options opts)
從輸入流中解碼位圖 public static Bitmap decodeStream(InputStreamis)
從字節數組中解碼生成不可變的位圖 public staticBitmap decodeByteArray(byte[] data, int offset, int length)
BitmapDrawable類: 繼承於Drawable,你可以從文件路徑、輸入流、XML文件以及Bitmap中創建。
常用的構造函數: Resourcesres=getResources();//獲取資源
publicBitmapDrawable(Resources res)——創建一個空的drawable。(Response用來指定初始時所用的像素密度)替代public BitmapDrawable()方法(此方法不處理像素密度)
publicBitmapDrawable(Resources res, Bitmap bitmap)——從位圖創建繪制
publicBitmapDrawable(Resources res, String filepath)——通過打開agiven文件路徑和位圖解碼創建繪制
publicBitmapDrawable(Resources res, java.io.InputStream is)——創建一個可繪制從給定的輸入流bydecoding位圖。


使用BitmapFactory解碼資源


import android.app.Activity;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ImageView;

public class Test extends Activity {
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
          ImageView imgView = (ImageView)findViewById(R.id.image3);
          
          imgView.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.icon) );
      }
}

//main.xml



  

  

  
  
  

  

  

  




捕獲和保存位圖

import java.io.File;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.View;

public class Test extends Activity {
  Uri myPicture = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
    public void captureImage(View view)
    {
        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(i, 0);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==0 && resultCode==Activity.RESULT_OK)
        {
             Bitmap myBitmap = (Bitmap) data.getExtras().get("data");
        }
    }
}


位圖大小

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Display;
import android.widget.ImageView;

public class Test extends Activity {
  final static int CAMERA_RESULT = 0;
  ImageView imv;
  String imageFilePath;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/a.jpg";
    File imageFile = new File(imageFilePath);
    Uri imageFileUri = Uri.fromFile(imageFile);
    Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
    startActivityForResult(i, CAMERA_RESULT);
  }

  protected void onActivityResult(int requestCode, int resultCode,
      Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    if (resultCode == RESULT_OK) {
      imv = (ImageView) findViewById(R.id.ReturnedImageView);
      Display currentDisplay = getWindowManager().getDefaultDisplay();
      BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
      bmpFactoryOptions.inJustDecodeBounds = true;
      Bitmap bmp = BitmapFactory.decodeFile(imageFilePath,
          bmpFactoryOptions);

      bmpFactoryOptions.inSampleSize = 2;
      bmpFactoryOptions.inJustDecodeBounds = false;
      bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
      imv.setImageBitmap(bmp);
    }
  }
}

//layout/main.xml


  



在畫布(Canvas)上繪制位圖

import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class Test extends Activity implements OnClickListener {
  ImageView chosenImageView;
  Button choosePicture;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    chosenImageView = (ImageView) this.findViewById(R.id.ChosenImageView);
    choosePicture = (Button) this.findViewById(R.id.ChoosePictureButton);

    choosePicture.setOnClickListener(this);
  }

  public void onClick(View v) {
    Intent choosePictureIntent = new Intent(Intent.ACTION_PICK,
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(choosePictureIntent, 0);
  }

  protected void onActivityResult(int requestCode, int resultCode,
      Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (resultCode == RESULT_OK) {
      Uri imageFileUri = intent.getData();
      try {
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(
                imageFileUri), null, bmpFactoryOptions);
        bmpFactoryOptions.inSampleSize = 2;

        bmpFactoryOptions.inJustDecodeBounds = false;
        bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(
                imageFileUri), null, bmpFactoryOptions);
        Bitmap alteredBitmap = Bitmap.createBitmap(bmp.getWidth(), bmp
            .getHeight(), bmp.getConfig());
        Canvas canvas = new Canvas(alteredBitmap);
        Paint paint = new Paint();
        canvas.drawBitmap(bmp, 0, 0, paint);
        ImageView alteredImageView = (ImageView) this
            .findViewById(R.id.AlteredImageView);
        alteredImageView.setImageBitmap(alteredBitmap);
        chosenImageView.setImageBitmap(bmp);
      } catch (FileNotFoundException e) {
        Log.v("ERROR", e.toString());
      }
    }
  }
}

//main.xml






Bitmap.createBitmap
import java.io.FileNotFoundException;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class Test extends Activity implements OnClickListener {
  Button choosePicture1, choosePicture2;
  ImageView compositeImageView;
  Bitmap bmp1, bmp2;
  Canvas canvas;
  Paint paint;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    compositeImageView = (ImageView) this
        .findViewById(R.id.CompositeImageView);

    choosePicture1 = (Button) this.findViewById(R.id.ChoosePictureButton1);
    choosePicture2 = (Button) this.findViewById(R.id.ChoosePictureButton2);

    choosePicture1.setOnClickListener(this);
    choosePicture2.setOnClickListener(this);
  }

  public void onClick(View v) {
    Intent choosePictureIntent = new Intent(Intent.ACTION_PICK,
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(choosePictureIntent, 1);
  }

  protected void onActivityResult(int requestCode, int resultCode,
      Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (resultCode == RESULT_OK) {
      Uri imageFileUri = intent.getData();
      bmp1 = loadBitmap(imageFileUri);
      Bitmap drawingBitmap = Bitmap.createBitmap(bmp1.getWidth(),
          bmp1.getHeight(), bmp1.getConfig());
      canvas = new Canvas(drawingBitmap);
      paint = new Paint();
      canvas.drawBitmap(bmp1, 0, 0, paint);
      paint.setXfermode(new PorterDuffXfermode(
          android.graphics.PorterDuff.Mode.MULTIPLY));
      canvas.drawBitmap(bmp2, 0, 0, paint);
      compositeImageView.setImageBitmap(drawingBitmap);
    }
  }

  private Bitmap loadBitmap(Uri imageFileUri) {
    Display currentDisplay = getWindowManager().getDefaultDisplay();

    float dw = currentDisplay.getWidth();
    float dh = currentDisplay.getHeight();

    Bitmap returnBmp = Bitmap.createBitmap((int) dw, (int) dh,
        Bitmap.Config.ARGB_4444);
    try {
      BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
      bmpFactoryOptions.inJustDecodeBounds = true;
      returnBmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions);
      bmpFactoryOptions.inSampleSize = 2;
      bmpFactoryOptions.inJustDecodeBounds = false;
      returnBmp = BitmapFactory.decodeStream(getContentResolver()
          .openInputStream(imageFileUri), null, bmpFactoryOptions);
    } catch (Exception e) {
      Log.v("ERROR", e.toString());
    }
    return returnBmp;
  }
}


在畫布上繪制位圖(使用矩陣)
import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class Test extends Activity implements OnClickListener {

  ImageView chosenImageView;
  Button choosePicture;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    chosenImageView = (ImageView) this.findViewById(R.id.ChosenImageView);
    choosePicture = (Button) this.findViewById(R.id.ChoosePictureButton);

    choosePicture.setOnClickListener(this);
  }

  public void onClick(View v) {
    Intent choosePictureIntent = new Intent(Intent.ACTION_PICK,
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(choosePictureIntent, 0);
  }

  protected void onActivityResult(int requestCode, int resultCode,
      Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (resultCode == RESULT_OK) {
      Uri imageFileUri = intent.getData();

      Display currentDisplay = getWindowManager().getDefaultDisplay();
      int dw = currentDisplay.getWidth();
      int dh = currentDisplay.getHeight() / 2 - 100;
      try {
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(
                imageFileUri), null, bmpFactoryOptions);

        bmpFactoryOptions.inSampleSize = 2;

        bmpFactoryOptions.inJustDecodeBounds = false;
        bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(
                imageFileUri), null, bmpFactoryOptions);

        Bitmap alteredBitmap = Bitmap.createBitmap(bmp.getWidth(), bmp
            .getHeight(), bmp.getConfig());
        Canvas canvas = new Canvas(alteredBitmap);
        Paint paint = new Paint();
        canvas.drawBitmap(bmp, 0, 0, paint);
        Matrix matrix = new Matrix();
        matrix.setValues(new float[] { 1, .5f, 0, 0, 1, 0, 0, 0, 1 });
        canvas.drawBitmap(bmp, matrix, paint);

        ImageView alteredImageView = (ImageView) this.findViewById(R.id.AlteredImageView);
        alteredImageView.setImageBitmap(alteredBitmap);

        chosenImageView.setImageBitmap(bmp);

      } catch (Exception e) {
        Log.v("ERROR", e.toString());
      }
    }
  }
}


//main.xml





創建一個位圖來畫

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.ImageView;

public class Test extends Activity {
  ImageView drawingImageView;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    drawingImageView = (ImageView) this.findViewById(R.id.DrawingImageView);
    Bitmap bitmap = Bitmap.createBitmap((int) getWindowManager()
        .getDefaultDisplay().getWidth(), (int) getWindowManager()
        .getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawingImageView.setImageBitmap(bitmap);

    Paint paint = new Paint();
    paint.setColor(Color.GREEN);
    paint.setTextSize(20);
    paint.setTypeface(Typeface.DEFAULT);
    Path p = new Path();
    p.moveTo(20, 20);
    p.lineTo(100, 150);
    p.lineTo(200, 220);
    canvas.drawTextOnPath("this is a test", p, 0, 0, paint);
  }
}



加載位圖和畫
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

public class Test extends Activity {
  class RenderView extends View {
    Bitmap bitmap1;
    Bitmap bitmap2;
    Rect dst = new Rect();

    public RenderView(Context context) {
      super(context);
      try {
        AssetManager assetManager = context.getAssets();
        InputStream inputStream = assetManager.open("a.png");
        bitmap1 = BitmapFactory.decodeStream(inputStream);
        inputStream.close();
        Log.d("Text",""+bitmap1.getConfig());
        inputStream = assetManager.open("b.png");
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_4444;
        bitmap2 = BitmapFactory.decodeStream(inputStream, null, options);
        inputStream.close();
        Log.d("BitmapText","" + bitmap2.getConfig());
      } catch (IOException e) {
        
      }
    }

    protected void onDraw(Canvas canvas) {
      dst.set(50, 50, 350, 350);
      canvas.drawBitmap(bitmap1, null, dst, null);
      canvas.drawBitmap(bitmap2, 100, 100, null);
      invalidate();
    }
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(new RenderView(this));
  }
}



總結一下:
1. 從資源中獲取位圖 可以使用BitmapDrawable或者BitmapFactory來獲取資源中的位圖。 當然,首先需要獲取資源: Resources res=getResources(); 使用BitmapDrawable獲取位圖 1. 使用BitmapDrawable (InputStream is)構造一個BitmapDrawable; 2. 使用BitmapDrawable類的getBitmap()獲取得到位圖; 通過Resource的函數:InputStream openRawResource(int id)獲取得到資源文件的數據流後,也可以通2種方法來獲取Bitmap,如下: 使用BitmapDrawable (A Drawable that wraps a bitmap and can be tiled,stretched, or aligned.) 使用BitmapDrawable (InputStream is)構造一個BitmapDrawable; 使用BitmapDrawable類的getBitmap()獲取得到位圖; BitmapDrawable也提供了顯示位圖等操作。 InputStreamis=res.openRawResource(R.drawable.pic180); // 讀取資源文件獲取輸入流 BitmapDrawablebmpDraw=new BitmapDrawable(is); Bitmapbmp=bmpDraw.getBitmap(); 或者: BitmapDrawablebmpDraw=(BitmapDrawable)res.getDrawable(R.drawable.pic180); Bitmapbmp=bmpDraw.getBitmap(); 使用BitmapFactory (Creates Bitmap objects from various sources, includingfiles, streams, and byte-arrays.) 使用BitmapFactory類decodeStream(InputStream is)解碼位圖資源,獲取位圖。 使用BitmapFactory類Bitmap bmp=BitmapFactory.decodeResource(res,R.drawable.pic180); 方法解碼位圖資源。 BitmapFactory的所有函數都是static,這個輔助類可以通過資源ID、路徑、文件、數據流等方式來獲取位圖。 以上方法在編程的時候可以自由選擇,在Android SDK中說明可以支持的圖片格式如下:png (preferred), jpg (acceptable), gif(discouraged),雖然bmp格式沒有明確說明,但是在Android SDK Support Media Format中是明確說明了。
2. 獲取位圖的信息 要獲取位圖信息,比如位圖大小、是否包含透明度、顏色格式等,獲取得到Bitmap就迎刃而解了,這些信息在Bitmap的函數中可以輕松獲取到。Android SDK中對Bitmap有詳細說明,閱讀起來也比較容易,不在此詳細說明,這裡只是輔助說明以下2點: 在Bitmap中對RGB顏色格式使用Bitmap.Config定義,僅包括ALPHA_8、ARGB_4444、ARGB_8888、RGB_565,缺少了一些其他的,比如說RGB_555,在開發中可能需要注意這個小問題; Bitmap還提供了compress()接口來壓縮圖片,不過AndroidSAK只支持PNG、JPG格式的壓縮;其他格式的需要Android開發人員自己補充了。
3. 顯示位圖 顯示位圖可以使用核心類Canvas,通過Canvas類的drawBirmap()顯示位圖,或者借助於BitmapDrawable來將Bitmap繪制到Canvas。當然,也可以通過BitmapDrawable將位圖顯示到View中。 轉換為BitmapDrawable對象顯示位圖 //獲取位圖 Bitmapbmp=BitmapFactory.decodeResource(res, R.drawable.pic180); // 轉換為BitmapDrawable對象 BitmapDrawable bmpDraw=newBitmapDrawable(bmp); // 顯示位圖 ImageView iv2 =(ImageView)findViewById(R.id.ImageView02); iv2.setImageDrawable(bmpDraw); 使用Canvas類顯示位圖 這兒采用一個繼承自View的子類Panel,在子類的OnDraw中顯示 Java代碼 public classMainActivity extends Activity { @Override public void onCreate(BundlesavedInstanceState) { super.onCreate(savedInstanceState); setContentView(new Panel(this)); } class Panel extends View{ public Panel(Context context) { super(context); } public void onDraw(Canvas canvas){ Bitmap bmp =BitmapFactory.decodeResource(getResources(), R.drawable.pic180); canvas.drawColor(Color.BLACK); canvas.drawBitmap(bmp, 10, 10,null); } } }
4. 位圖縮放 (1)將一個位圖按照需求重畫一遍,畫後的位圖就是我們需要的了,與位圖的顯示幾乎一樣:drawBitmap(Bitmap bitmap, Rect src, Rect dst,Paint paint)。 (2)在原有位圖的基礎上,縮放原位圖,創建一個新的位圖:CreateBitmap(Bitmap source, int x, int y,int width, int height, Matrix m, boolean filter) (3)借助Canvas的scale(float sx, float sy) (Preconcat the current matrix with thespecified scale.),不過要注意此時整個畫布都縮放了。 (4)借助Matrix: Bitmap bmp =BitmapFactory.decodeResource(getResources(), R.drawable.pic180); Matrix matrix=new Matrix(); matrix.postScale(0.2f,0.2f); Bitmapdstbmp=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(), bmp.getHeight(),matrix,true); canvas.drawColor(Color.BLACK); canvas.drawBitmap(dstbmp,10, 10, null);
5. 位圖旋轉 同樣,位圖的旋轉也可以借助Matrix或者Canvas來實現。Matrix在線性代數中都學習過,Android SDK提供了Matrix類,可以通過各種接口來設置矩陣。結合上面的例子程序,將位圖縮放例子程序在顯示位圖的時候前,增加位圖旋轉功能,修改代碼如下: Matrix matrix = new Matrix(); //matrix.postScale(0.5f,0.5f); matrix.setRotate(90,120,130); canvas.drawBitmap(mbmpTest,matrix, mPaint); 除了這種方法之外,我們也可以在使用Bitmap提供的函數如下: public staticBitmap createBitmap (Bitmap source, int x, int y, int width, int height, Matrixm, boolean filter),在原有位圖旋轉的基礎上,創建新位圖。

2014.2.5
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved