Bitmap、Drawable是什么?
Bitmap: 一个个位图像素映射到内存的数据存储器
Drawable:可以自带绘制规则的绘制类,通过 Canvas
来进⾏绘制的上层⼯具
它们的对象互转实现是怎样的?
kotlin的ktx为我们提供了很便利的方式,不像之前我们还需要自己写(其实是从网上拷贝)一大串实现代码
//drawable -> bitmap
drawable.toBitmap()
//bitmap -> drawable
bitmap.toDrawable()
它背后实现其实和我们之前使用java在网上找的 代码基本是一样的
//drawable -> bitmap
fun Drawable.toBitmap(
@Px width: Int = intrinsicWidth,
@Px height: Int = intrinsicHeight,
config: Config? = null
): Bitmap {
//1.如果是BitmapDrawable类型,直接拿它的bitmap直接转换成需要的尺寸
if (this is BitmapDrawable) {
if (config == null || bitmap.config == config) {
// Fast-path to return original. Bitmap.createScaledBitmap will do this check, but it
// involves allocation and two jumps into native code so we perform the check ourselves.
if (width == intrinsicWidth && height == intrinsicHeight) {
return bitmap
}
return Bitmap.createScaledBitmap(bitmap, width, height, true)
}
}
val (oldLeft, oldTop, oldRight, oldBottom) = bounds
val bitmap = Bitmap.createBitmap(width, height, config ?: Config.ARGB_8888)
setBounds(0, 0, width, height)
//2. 否则就根据drawable自己的规则,直接绘制出来
draw(Canvas(bitmap))
setBounds(oldLeft, oldTop, oldRight, oldBottom)
return bitmap
}
- 如果是
BitmapDrawable
类型,直接拿它的bitmap
转换成需要的尺寸 - 否则就根据
drawable
自己的规则,绘制出来
//bitmap -> drawable
inline fun Bitmap.toDrawable(resources: Resources) = BitmapDrawable(resources, this)
bitmap -> drawable
很简单,直接创建BitmapDrawable
对象,内部实现就是再通过Drawable的draw
方法,把这个bitmap
画上去
自定义Drawable真的没有用吗?
很多人说自定义Drawable
其实没有用,笔者觉得只是源码给了很多常用的子Drawable
,让我们很少自定义它,所以感觉没有用
自定义Drawable很重要的作用是:复用绘制的代码
比如我们在多个自定义view
需要用到同样的绘制代码,就可以考虑是否可以自定义一种Drawable
去复用这段代码呢