Android Bitmap

Tips: KTX可以直接将bitmap转为Drawable

复制代码
     val drawable1 = ColorDrawable()
        val bitmap1 = drawable1.toBitmap()

Drawable 也可以直接转为BitMap

复制代码
     val bitmap = Bitmap.createBitmap(20,20,Bitmap.Config.ARGB_8888)
        val drawable = bitmap.toDrawable(resources)

toDrawable源码:

复制代码
/** Create a [BitmapDrawable] from this [Bitmap]. */
public inline fun Bitmap.toDrawable(
    resources: Resources
): BitmapDrawable = BitmapDrawable(resources, this)

toBitmap源码:

复制代码
public fun Drawable.toBitmap(
    @Px width: Int = intrinsicWidth,
    @Px height: Int = intrinsicHeight,
    config: Config? = null
): Bitmap {
    if (this is BitmapDrawable) {
        if (bitmap == null) {
            // This is slightly better than returning an empty, zero-size bitmap.
            throw IllegalArgumentException("bitmap is null")
        }
        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 == bitmap.width && height == bitmap.height) {
                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)
    draw(Canvas(bitmap))

    setBounds(oldLeft, oldTop, oldRight, oldBottom)
    return bitmap
}

Bitmap: bit 位 ,map 映射,也就是像素映射到内存对象

Drawable: ColorDrawable 默认范围0.0 需要制定Bounds

drawable 内部维持绘制规则 可以使bitmap color 等

bitmap是像素信息

bitmap和drawable 互转本质上是创建彼此的一个对象实例

bitmapDrawable通过canvas.drawBitmap

自定义Drawable:

drawable 是一个接口 需要实现四个方法:

复制代码
class MatchDrawable : Drawable() {
    override fun draw(canvas: Canvas) {

    }

    override fun setAlpha(alpha: Int) {
    }

    override fun setColorFilter(colorFilter: ColorFilter?) {
    }

    override fun getOpacity(): Int {
    }
}

setColor KTX 可以写 "#0085d0".toColorInt

大多数情况可以使用系统自带的drawable 比如 colorDrawable BitmapDrawable等

相关推荐
duwei_wang1 小时前
[Android]-Admob配置过多导致的慢消息
android
雨白2 小时前
发送自定义广播
android
雨白3 小时前
深入理解广播机制 (BroadcastReceiver)
android
婵鸣空啼7 小时前
GD图像处理与SESSiON
android
sunly_7 小时前
Flutter:导航固定背景图,滚动时导航颜色渐变
android·javascript·flutter
用户2018792831678 小时前
简单了解android.permission.MEDIA_CONTENT_CONTROL权限
android
_一条咸鱼_8 小时前
Android Runtime类卸载条件与资源回收策略(29)
android·面试·android jetpack
顾林海8 小时前
Android Bitmap治理全解析:从加载优化到泄漏防控的全生命周期管理
android·面试·性能优化
砖厂小工8 小时前
Now In Android 精讲 8 - Gradle build-logic 现代构建逻辑组织方式
android
玲小珑8 小时前
Auto.js 入门指南(八)高级控件与 UI 自动化
android·前端