Drawable与Bitmap的转换及缩放

Bitmap与Drawable的互转及缩放的实现。

Bitmap转Drawable

1
2
3
4
5
6
7
public Drawable bitmapToDrawable(Bitmap bitmap) {
if (bitmap != null) {
return new BitmapDrawable(getResource(), bitmap);
}

return null;
}

Drawable转Bitmap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public Bitmap drawableToBitmap(Drawable drawable) {
if (drawable == null) {
return null;
}

if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}

try {
Bitmap bitmap;
if (drawable instanceof ColorDrawable) {
bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

Bitmap缩放

1
2
3
4
5
6
7
8
9
10
11
 private Bitmap zoomBitmap(Bitmap sourceBitmap, float newWidth, float newHeight) {
float width = sourceBitmap.getWidth();
float height = sourceBitmap.getHeight();
Matrix matrix = new Matrix();
// 计算宽高缩放率
float scaleWidth = newWidth / width;
float scaleHeight = newHeight / height;
// 对图片进行缩放
matrix.postScale(scaleWidth, scaleHeight);
return Bitmap.createBitmap(sourceBitmap, 0, 0, (int) width, (int) height, matrix, true);
}
,