package com.example.base.extensions

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.PixelFormat
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable

/**
 * drawable扩展工具类
 */


/**
 * drawable转bitmap
 *
 * @return bitmap
 */
fun Drawable.toBitmap(): Bitmap {

    if (this is BitmapDrawable) {
        return this.bitmap
    }
    // 获取drawable长度、宽度
    val width = this.intrinsicWidth
    val height = this.intrinsicHeight

    // 获取drawable的颜色
    val config =
        if (this.opacity != PixelFormat.OPAQUE) Bitmap.Config.ARGB_8888 else Bitmap.Config.RGB_565


    // 创建bitmap
    val bitmap: Bitmap = if (width <= 0 || height <= 0) {
        Bitmap.createBitmap(1, 1, config)
    } else {
        Bitmap.createBitmap(width, height, config)
    }
    // 创建bitmap画布
    val canvas = Canvas(bitmap)
    this.setBounds(0, 0, canvas.width, canvas.height)

    // 将drawable 内容画到画布中
    this.draw(canvas)
    return bitmap
}

