Android从Drawable资源Id直接生成Bitmap,Kotlin
Kotlin
val t1 = System.currentTimeMillis()
val bmp = getBmpFromDrawId(this, R.mipmap.ic_launcher_round)
Log.d("fly", "1 ${bmp?.byteCount} h=${bmp?.height} w=${bmp?.width} cost time=${System.currentTimeMillis() - t1}")
val t2 = System.currentTimeMillis()
val scaleBmp = Bitmap.createScaledBitmap(bmp!!, 800, 800, true)
Log.d("fly", "2 ${scaleBmp.byteCount} h=${scaleBmp.height} w=${scaleBmp.width} cost time=${System.currentTimeMillis() - t2}")
Kotlin
private fun getBmpFromDrawId(context: Context, drawId: Int): Bitmap? {
val drawable = ContextCompat.getDrawable(context, drawId)
val bitmap = drawable?.let {
Bitmap.createBitmap(
it.intrinsicWidth,
it.intrinsicHeight,
Bitmap.Config.ARGB_8888
)
}
val canvas = bitmap?.let { Canvas(it) }
if (canvas != null) {
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
}
return bitmap
}