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
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="fill_parent"> <ImageView android:id="@+id/image1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/icon" /> <ImageView android:id="@+id/image2" android:layout_width="125dip" android:layout_height="25dip" android:src="#555555" /> </LinearLayout> <LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="fill_parent"> <ImageView android:id="@+id/image3" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ImageView android:id="@+id/image4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/icon" android:scaleType="centerInside" android:maxWidth="35dip" android:maxHeight="50dip" /> </LinearLayout> </LinearLayout>
捕獲和保存位圖 
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 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ImageView android:id="@+id/ReturnedImageView" android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageView> </LinearLayout>

在畫布(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 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Choose Picture" android:id="@+id/ChoosePictureButton"/> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ChosenImageView"></ImageView> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/AlteredImageView"></ImageView> </LinearLayout>
 
 

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 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Choose Picture" android:id="@+id/ChoosePictureButton"/> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ChosenImageView"></ImageView> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/AlteredImageView"></ImageView> </LinearLayout>
創建一個位圖來畫 
 
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) ,在原有位圖旋轉的基礎上,創建新位圖。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM