package com.base.scanqr.ui.widget

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView


class TransparentSrcInImageView : AppCompatImageView {

    private lateinit var paint: Paint

    constructor(context: Context) : super(context) {
        intiPorterDuffMode()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        intiPorterDuffMode()
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        intiPorterDuffMode()
    }

    private fun intiPorterDuffMode() {
        // 设置混合模式
        val xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
        paint = Paint()
        paint.setXfermode(xfermode)
        setLayerType(LAYER_TYPE_SOFTWARE, paint) // 需要软件绘制
    }

    override fun onDraw(canvas: Canvas) {
        // 先绘制背景（如果有）
        super.onDraw(canvas)

        // 绘制图片，使用自定义的混合模式
        drawBitmap(canvas)
    }

    private fun drawBitmap(canvas: Canvas) {

        val drawable = getDrawable()
        val bitmap = drawableToBitmap(drawable)
        if (bitmap != null) {
            canvas.drawBitmap(bitmap, 0f, 0f, paint)
        }
    }

    private fun drawableToBitmap(drawable: Drawable): Bitmap? {
        if (drawable is BitmapDrawable) {
            return drawable.bitmap
        }
        var bitmap: Bitmap? = null
        try {
            bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
            val canvas = Canvas(bitmap)
            drawable.setBounds(0, 0, canvas.width, canvas.height)
            drawable.draw(canvas)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return bitmap
    }


}