drawable的定义如下:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!--size的比例控制在16:9,对于纯色渐变图,在转换为bitmap时候,内存占用最小,
但是不影响bitmap的绘制效果。-->
<size
android:width="9dp"
android:height="16dp" />
<gradient
android:angle="0"
android:endColor="#FF192F40"
android:startColor="#FF320707" />
</shape>
使用代码将其读取并转换为bitmap绘制在ImageView上面
@JvmStatic
fun drawableToBitmap(drawable: Drawable): Bitmap? {
if (drawable is BitmapDrawable) {
return drawable.bitmap
}
MLog.warn(TAG, "drawableToBitmap called " +
"drawable.intrinsicWidth width :${drawable.intrinsicWidth} ," +
" drawable.intrinsicHeight :${drawable.intrinsicHeight} ")
val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight,
Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
MLog.warn(TAG, "drawableToBitmap called return " +
"bitmap width :${bitmap.width} , height :${bitmap.height} " +
"size : ${bitmap.allocationByteCount / 1024} kb")
return bitmap
}
1、
size设置如下:
<size
android:width="1125dp"
android:height="1995dp" />
日志输出:
2020-11-18 20:24:41.607 7225-7225/com.yy.dreamer W/EnhanceDrawableResourceParse: drawableToBitmap called drawable.intrinsicWidth width :3375 , drawable.intrinsicHeight :5985
2020-11-18 20:24:41.695 7225-7225/com.yy.dreamer W/EnhanceDrawableResourceParse: drawableToBitmap called return bitmap width :3375 , height :5985 size : 78903 kb
78903 kb = 77MB
2、
size设置如下:
<size
android:width="720dp"
android:height="1280dp" />
日志输出:
2020-11-18 20:18:54.169 3864-3864/com.yy.dreamer W/EnhanceDrawableResourceParse: drawableToBitmap called drawable.intrinsicWidth width :2160 , drawable.intrinsicHeight :3840
2020-11-18 20:18:54.207 3864-3864/com.yy.dreamer W/EnhanceDrawableResourceParse: drawableToBitmap called return bitmap width :2160 , height :3840 size : 31744 kb
31744 kb = 31MB
3、
size设置如下:
<size
android:width="72dp"
android:height="128dp" />
日志输出:
2020-11-18 20:22:46.559 6132-6132/com.yy.dreamer W/EnhanceDrawableResourceParse: drawableToBitmap called drawable.intrinsicWidth width :216 , drawable.intrinsicHeight :384
2020-11-18 20:22:46.561 6132-6132/com.yy.dreamer W/EnhanceDrawableResourceParse: drawableToBitmap called return bitmap width :216 , height :384 size : 324 kb
324 kb = 0.31MB
4、
size设置如下:
<size
android:width="9dp"
android:height="16dp" />
日志输出:
2020-11-18 20:27:16.450 8343-8343/com.yy.dreamer W/EnhanceDrawableResourceParse: drawableToBitmap called drawable.intrinsicWidth width :27 , drawable.intrinsicHeight :48
2020-11-18 20:27:16.451 8343-8343/com.yy.dreamer W/EnhanceDrawableResourceParse: drawableToBitmap called return bitmap width :27 , height :48 size : 5 kb
5kb = 0.0048MB
结论:
在Android xml文件定义的shape Drawable ,可以尽量小的定义size,这样在转换为bitmap时候,可以最大限度的节省内存,但是不影响绘制效果。