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等

相关推荐
coderlin_7 小时前
BI布局拖拽 (1) 深入react-gird-layout源码
android·javascript·react.js
2501_915918417 小时前
Fiddler中文版全面评测:功能亮点、使用场景与中文网资源整合指南
android·ios·小程序·https·uni-app·iphone·webview
wen's8 小时前
React Native安卓刘海屏适配终极方案:仅需修改 AndroidManifest.xml!
android·xml·react native
编程乐学9 小时前
网络资源模板--基于Android Studio 实现的聊天App
android·android studio·大作业·移动端开发·安卓移动开发·聊天app
没有了遇见12 小时前
Android 通过 SO 库安全存储敏感数据,解决接口劫持问题
android
hsx66612 小时前
使用一个 RecyclerView 构建复杂多类型布局
android
hsx66612 小时前
利用 onMeasure、onLayout、onDraw 创建自定义 View
android
守城小轩12 小时前
Chromium 136 编译指南 - Android 篇:开发工具安装(三)
android·数据库·redis
whysqwhw12 小时前
OkHttp平台抽象机制分析
android
hsx66613 小时前
Android 内存泄漏避坑
android