• Android Bitmap


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

    1. val drawable1 = ColorDrawable()
    2. val bitmap1 = drawable1.toBitmap()

    Drawable 也可以直接转为BitMap 

    1. val bitmap = Bitmap.createBitmap(20,20,Bitmap.Config.ARGB_8888)
    2. val drawable = bitmap.toDrawable(resources)

    toDrawable源码:

    1. /** Create a [BitmapDrawable] from this [Bitmap]. */
    2. public inline fun Bitmap.toDrawable(
    3. resources: Resources
    4. ): BitmapDrawable = BitmapDrawable(resources, this)

    toBitmap源码:

    1. public fun Drawable.toBitmap(
    2. @Px width: Int = intrinsicWidth,
    3. @Px height: Int = intrinsicHeight,
    4. config: Config? = null
    5. ): Bitmap {
    6. if (this is BitmapDrawable) {
    7. if (bitmap == null) {
    8. // This is slightly better than returning an empty, zero-size bitmap.
    9. throw IllegalArgumentException("bitmap is null")
    10. }
    11. if (config == null || bitmap.config == config) {
    12. // Fast-path to return original. Bitmap.createScaledBitmap will do this check, but it
    13. // involves allocation and two jumps into native code so we perform the check ourselves.
    14. if (width == bitmap.width && height == bitmap.height) {
    15. return bitmap
    16. }
    17. return Bitmap.createScaledBitmap(bitmap, width, height, true)
    18. }
    19. }
    20. val (oldLeft, oldTop, oldRight, oldBottom) = bounds
    21. val bitmap = Bitmap.createBitmap(width, height, config ?: Config.ARGB_8888)
    22. setBounds(0, 0, width, height)
    23. draw(Canvas(bitmap))
    24. setBounds(oldLeft, oldTop, oldRight, oldBottom)
    25. return bitmap
    26. }

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

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

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

    bitmap是像素信息

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

    bitmapDrawable通过canvas.drawBitmap

    自定义Drawable:

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

    1. class MatchDrawable : Drawable() {
    2. override fun draw(canvas: Canvas) {
    3. }
    4. override fun setAlpha(alpha: Int) {
    5. }
    6. override fun setColorFilter(colorFilter: ColorFilter?) {
    7. }
    8. override fun getOpacity(): Int {
    9. }
    10. }

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

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

  • 相关阅读:
    抢购狂欢:跨境电商的区域购物节
    word添加行号
    15.cuBLAS开发指南中文版--cuBLAS中的Level-1函数rotg()
    1069 The Black Hole of Numbers
    快速学会ACL技术
    对数几率回归的损失函数,线性回归损失函数公式
    [Linux打怪升级之路]-环境变量
    将一个无向图变成一个双联通图所需添加的最小边数
    BGP高级特性——BGP路由控制
    数码管显示驱动芯片 CH450
  • 原文地址:https://blog.csdn.net/qq_29769851/article/details/132849425