Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 基礎入門教程——Bitmap(位圖)全解析 Part 1

編輯:關於 Android 程式設計


本節引言

上一節我們講解了 Android 中 13 種 Drawable 類型,不知道你有沒有應用到自己的項目裡?本節要探討 Bitmap(位圖)的使用。開始之前,先釐清幾個容易混淆的名詞:

Drawable:通用的圖形對象,用於裝載 PNG、JPG 等圖像,也可以是前面學過的 13 種 Drawable 可視化對象,可以理解為一個用來放畫的「畫框」。
Bitmap(位圖):可看作一個「畫架」,先把畫放上去,再進行獲取資訊、旋轉切割、放大縮小等處理。
Canvas(畫布):如其名,一塊畫布,可在上面作畫,既能用 Paint(畫筆)畫各種形狀或寫字,也能用 Path(路徑)連接多個點成圖形。
Matrix(矩陣):用於圖形特效處理,包括顏色矩陣(ColorMatrix),以及圖像的平移、縮放、旋轉、傾斜等。

上述這些都是 Android 底層圖形類 android.graphics 提供的接口。廢話不多說,開始本節內容。


一、了解 Bitmap、BitmapFactory、BitmapFactory.Options

打開 Bitmap 類源碼,你會看到它的構造方法上有這樣一段說明:

大意是:Bitmap 的構造方法是私有的,外部無法實例化,只能透過 JNI 創建。好在系統提供了一個接口類——BitmapFactory。打開它並查看 Structure 可以發現,它提供了大量 decodeXxx 方法,能透過各種形式創建 Bitmap:

further 你會發現每個方法都有一個 Options 類型的參數,點進去一看,原來是個靜態內部類 BitmapFactory.Options,用於設定 decode 時的選項:

透過設置某些參數(例如把 inJustDecodeBounds 設為 true 來避免 OOM),就能控制解碼行為。至於 Bitmap 本身的方法眾多,這裡挑幾個常用的來講。


二、Bitmap 常用方法

普通方法

public boolean compress(Bitmap.CompressFormat format, int quality, OutputStream stream):把位圖壓縮到指定的 OutputStream,可理解為將 Bitmap 保存到文件。
format:格式,如 PNG、JPG;quality:壓縮質量 0-100,0 最低、100 最高(PNG 無損會忽略品質設定);stream:輸出流。返回值代表是否成功壓縮。
void recycle():回收位圖佔用的內存空間,並標記為 Dead。
boolean isRecycled():判斷位圖內存是否已釋放。
int getWidth() / int getHeight():獲取位圖寬高。
boolean isMutable():圖片是否可修改。
int getScaledWidth(Canvas canvas) / int getScaledHeight(Canvas canvas):獲取指定密度轉換後的寬高。

靜態方法:

Bitmap createBitmap(Bitmap src):以 src 為原圖生成不可變的新圖像。
Bitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter):以 src 為原圖,指定新圖的寬高及是否縮放。
Bitmap createBitmap(int width, int height, Config config):創建指定格式、大小的位圖。
Bitmap createBitmap(Bitmap source, int x, int y, int width, int height):以 source 為原圖,指定起始坐標與新圖寬高。
Bitmap createBitmap(Bitmap source, int x, int y, int width, int height, Matrix m, boolean filter)。

BitmapFactory.Options 可設置參數:

boolean inJustDecodeBounds——設為 true 時不獲取圖片、不分配內存,但會返回圖片的寬高資訊。
int inSampleSize——圖片縮放倍數,設為 4 則寬高各為原來的 1/4,面積為原來的 1/16。
int outWidth——獲取圖片的寬度值。
int outHeight——獲取圖片的高度值。
int inDensity——用於位圖的像素壓縮比。
int inTargetDensity——用於目標位圖的像素壓縮比。
boolean inScaled——設為 true 時進行圖片壓縮,從 inDensity 到 inTargetDensity。


三、獲取 Bitmap 位圖

從資源中獲取位圖有兩種方式:BitmapDrawable 或 BitmapFactory。

BitmapDrawable 方法:可以構造一個 BitmapDrawable 對象,例如透過流構建:

 BitmapDrawable bmpMeizi = new BitmapDrawable(getAssets().open(pic_meizi.jpg)); Bitmap mBitmap = bmpMeizi.getBitmap(); img_bg.setImageBitmap(mBitmap);

BitmapFactory 方法:都是靜態方法,可直接調用,支援資源 ID、路徑、文件、數據流等多種來源:

 //通過資源ID private Bitmap getBitmapFromResource(Resources res, int resId) { return BitmapFactory.decodeResource(res, resId); } //文件 private Bitmap getBitmapFromFile(String pathName) { return BitmapFactory.decodeFile(pathName); } //字節數組 public Bitmap Bytes2Bimap(byte[] b) { if (b.length != 0) { return BitmapFactory.decodeByteArray(b, 0, b.length); } else { return null; } } //輸入流 private Bitmap getBitmapFromStream(InputStream inputStream) { return BitmapFactory.decodeStream(inputStream); } 

四、獲取 Bitmap 的相關信息

只要取得 Bitmap 對象,就能呼叫相關方法獲取參數,如 getByteCount 取得大小、getHeight 與 getWidth 取得寬高等,這裡不再贅述,可自行查閱文檔。


五、摳圖片上的某一角下來

有時想把圖片的某一角摳下來,直接透過 Bitmap 的 createBitmap() 即可,參數依次為:處理的 bitmap 對象、起始 x/y 坐標,以及截取的寬高。

 Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(), R.mipmap.pic_meizi); Bitmap bitmap2 = Bitmap.createBitmap(bitmap1,100,100,200,200); img_bg = (ImageView) findViewById(R.id.img_bg); img_bg.setImageBitmap(bitmap2);

運行效果圖:

原圖: 切下來的一角:


六、對 Bitmap 進行縮放

這裡不使用 Matrix,而是直接採用 Bitmap 提供的 createScaledBitmap 實現,參數依次是:處理的 bitmap 對象、縮放後的寬高。


七、使用 Bitmap 進行截屏

運行效果圖:

實現代碼:

 public class MainActivity extends AppCompatActivity { static ByteArrayOutputStream byteOut = null; private Bitmap bitmap = null; private Button btn_cut; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn_cut = (Button) findViewById(R.id.btn_cut); btn_cut.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { captureScreen(); } }); } public void captureScreen() { Runnable action = new Runnable() { @Override public void run() { final View contentView = getWindow().getDecorView(); try{ Log.e(HEHE,contentView.getHeight()+:+contentView.getWidth()); bitmap = Bitmap.createBitmap(contentView.getWidth(), contentView.getHeight(), Bitmap.Config.ARGB_4444); contentView.draw(new Canvas(bitmap)); ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteOut); savePic(bitmap, sdcard/short.png); }catch (Exception e){e.printStackTrace();} finally { try{ if (null != byteOut) byteOut.close(); if (null != bitmap && !bitmap.isRecycled()) { // bitmap.recycle(); bitmap = null; } }catch (IOException e){e.printStackTrace();} } } }; try { action.run(); } catch (Exception e) { e.printStackTrace(); } } private void savePic(Bitmap b, String strFileName) { FileOutputStream fos = null; try { fos = new FileOutputStream(strFileName); if (null != fos) { boolean success= b.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.flush(); fos.close(); if(success) Toast.makeText(MainActivity.this, 截屏成功, Toast.LENGTH_SHORT).show(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }

代碼分析:

程式碼非常簡單:final View contentView = getWindow().getDecorView(); 這句取得當前 XML 根節點的 View,接著設定截屏尺寸、呼叫 contentView.draw(new Canvas(bitmap)); 完成繪製,然後把 bitmap 轉為流並寫入 SD 卡即可。從結果也能看出,截圖截取的是該 App 的內容而已;若要截取整個全屏,可自行深入研究。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved