package com.xty.common

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Matrix
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.LevelListDrawable
import android.text.Html
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition


class MyImageGetter(var context: Context,var text:TextView):Html.ImageGetter {
    override fun getDrawable(source: String?): Drawable {
        val drawable: LevelListDrawable = LevelListDrawable()
        Glide.with(context).asBitmap().load(source).into(object : SimpleTarget<Bitmap?>() {


            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap?>?) {
                if (resource != null) {
                    val bitmapDrawable = BitmapDrawable(context.resources,resource)

                    drawable.addLevel(1, 1, bitmapDrawable)
                    drawable.setBounds(0, 0, resource.width, resource.height)

                    drawable.setLevel(1)
                    //防止图文重叠
                    text.invalidate()
                    text.text = text.getText()
                }
            }
        })
        return drawable
    }

    fun resizeBitmap(bitmap: Bitmap, w: Float, h: Float): Bitmap? {
        val width: Int = bitmap.getWidth()
        val height: Int = bitmap.getHeight()
        val scaleWidth = w.toFloat() / width
        val scaleHeight = h.toFloat() / height
        val matrix = Matrix()
        matrix.postScale(scaleWidth, scaleHeight)
        return Bitmap.createBitmap(
            bitmap, 0, 0, width,
            height, matrix, true
        )
    }
}