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等

相关推荐
沐言人生2 小时前
Android10 Framework—Init进程-9.服务端属性值初始化
android·android studio·android jetpack
追光天使2 小时前
【Mac】和【安卓手机】 通过有线方式实现投屏
android·macos·智能手机·投屏·有线
小雨cc5566ru2 小时前
uniapp+Android智慧居家养老服务平台 0fjae微信小程序
android·微信小程序·uni-app
一切皆是定数3 小时前
Android车载——VehicleHal初始化(Android 11)
android·gitee
一切皆是定数3 小时前
Android车载——VehicleHal运行流程(Android 11)
android
problc3 小时前
Android 组件化利器:WMRouter 与 DRouter 的选择与实践
android·java
图王大胜4 小时前
Android SystemUI组件(11)SystemUIVisibility解读
android·framework·systemui·visibility
服装学院的IT男8 小时前
【Android 13源码分析】Activity生命周期之onCreate,onStart,onResume-2
android
Arms2068 小时前
android 全面屏最底部栏沉浸式
android
服装学院的IT男8 小时前
【Android 源码分析】Activity生命周期之onStop-1
android