drawable的定義如下:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!--size的比例控制在16:9,對于純色漸變圖献起,在轉(zhuǎn)換為bitmap時(shí)候蛛株,內(nèi)存占用最小抓半,
但是不影響bitmap的繪制效果扔字。-->
<size
android:width="9dp"
android:height="16dp" />
<gradient
android:angle="0"
android:endColor="#FF192F40"
android:startColor="#FF320707" />
</shape>
使用代碼將其讀取并轉(zhuǎn)換為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設(shè)置如下:
<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設(shè)置如下:
<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設(shè)置如下:
<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設(shè)置如下:
<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
結(jié)論:
在Android xml文件定義的shape Drawable 舵鳞,可以盡量小的定義size震檩,這樣在轉(zhuǎn)換為bitmap時(shí)候,可以最大限度的節(jié)省內(nèi)存蜓堕,但是不影響繪制效果抛虏。