Drawable轉換為Bitmap兩種方法

銳湃發表於2015-11-10

想拿到點陣圖的Bitmap,有兩種辦法,至於那種好,可能要看是在什麼情況下了

1,根據已有的Drawable建立一個新的Bitmap:

  private Bitmap bitmap;
  private void drawableToBitamp(Drawable drawable)
  {
          int w = drawable.getIntrinsicWidth();
          int h = drawable.getIntrinsicHeight();
          System.out.println("Drawable轉Bitmap");
          Bitmap.Config config = 
                  drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                          : Bitmap.Config.RGB_565;
         bitmap = Bitmap.createBitmap(w,h,config);
         //注意,下面三行程式碼要用到,否在在View或者surfaceview裡的canvas.drawBitmap會看不到圖
         Canvas canvas = new Canvas(bitmap);   
         drawable.setBounds(0, 0, w, h);   
         drawable.draw(canvas);
     }

2,直接從現有的Drawable中取出Bitmap:

 private Bitmap bitmap;
 
 private void drawableToBitamp(Drawable drawable)
 {
         BitmapDrawable bd = (BitmapDrawable) drawable;
         bitmap = bd.getBitmap();
 }

轉自:http://www.cnblogs.com/JD85/archive/2012/01/26/2329872.html

相關文章