Drawable和Bitamp

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
}

  1. 如果是BitmapDrawable类型,直接拿它的bitmap转换成需要的尺寸
  2. 否则就根据drawable自己的规则,绘制出来
//bitmap -> drawable
inline fun Bitmap.toDrawable(resources: Resources) = BitmapDrawable(resources, this)

bitmap -> drawable很简单,直接创建BitmapDrawable对象,内部实现就是再通过Drawable的draw方法,把这个bitmap画上去

自定义Drawable真的没有用吗?

很多人说自定义Drawable其实没有用,笔者觉得只是源码给了很多常用的子Drawable,让我们很少自定义它,所以感觉没有用

自定义Drawable很重要的作用是:复用绘制的代码

比如我们在多个自定义view需要用到同样的绘制代码,就可以考虑是否可以自定义一种Drawable去复用这段代码呢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值