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等

相关推荐
fengci.32 分钟前
CTF+随机困难题目
android·开发语言·前端·学习·php
Le_ee1 小时前
SWPUCTF 2025 秋季新生赛wp2
android
pengyu2 小时前
【Kotlin 协程修仙录 · 金丹境 · 初阶】 | 并发艺术:async/await 与并发组合的优雅之道
android·kotlin
沐言人生3 小时前
ReactNative 源码分析3——ReactActivity之初始化RN应用
android·react native
YaBingSec4 小时前
网络安全靶场WP:Grafana 任意文件读取漏洞(CVE-2021-43798)
android·笔记·安全·web安全·ssh·grafana
YF02114 小时前
彻底解决Android非SDK接口绕过限制的深度实践
android·google·app
IVEN_4 小时前
Gradle 依赖下载 403 Forbidden 修复:全局镜像配置实战
android·后端
恋猫de小郭4 小时前
Flutter 3.44 发布前夕,官方宣布 SwiftPM 将完全取代 CocoaPods
android·前端·flutter
黄林晴5 小时前
重磅发布!KMP 双端订阅支付彻底封神,一套代码搞定 iOS+Android
android·kotlin
Carson带你学Android5 小时前
别再乱学了!深度解读 Google 官方发布 Android 6 大核心 Skills
android·前端·ai编程