方式1: 判断drawable 是否为BitmapDrawable
- 直接强转 Drawable 为 BitmapDrawable, 然后调用getBitmap() 函数返回Bitmap
方式2: 使用Canvas 绘制Bitmap
- 创建Bitmap画布对象
- 判断是否为ColorDrawable , 是的话, width = height =2 ?
- 不是直接按照 drawable 的宽高, 和 ARGB_8888 创建一个 Bitmap
- 调用 drawable.draw(canvas) 函数绘制图像, 并将drawable 保存在 Bitmap 上
private Bitmap getBitmapFromDrawable(Drawable drawable) {
if (drawable == null) {
return null;
}
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
try {
Bitmap bitmap;
//颜色Drawable
if (drawable instanceof ColorDrawable) {
//宽为2, 高为2 ??
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 的内容绘制到 bitmap的canvas 上面去.
drawable.draw(canvas);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}