Glide 圆角自定义设置上下左右

65 阅读1分钟
package com.xscore.utils

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import java.security.MessageDigest

/**
 * @Author: fenr
 * 时间: 2024/9/18
 * 类名: ACTIVITY
 * 简述: 自定义Glide圆角 可单独设置上 下 左 右圆角
 *
 */
class RoundedCornersTransformation (
    private val topLeft: Float,
    private val topRight: Float,
    private val bottomRight: Float,
    private val bottomLeft: Float
) : BitmapTransformation() {

    override fun updateDiskCacheKey(messageDigest: MessageDigest) {
        messageDigest.update((ID + topLeft + topRight + bottomRight + bottomLeft).toByteArray(Charsets.UTF_8))
    }

    override fun transform(pool: BitmapPool, toTransform: Bitmap, outWidth: Int, outHeight: Int): Bitmap {
        // 从 BitmapPool 获取位图
        val roundedBitmap = pool.get(toTransform.width, toTransform.height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(roundedBitmap)
        val paint = Paint(Paint.ANTI_ALIAS_FLAG)

        val path = Path()
        val rect = RectF(0f, 0f, toTransform.width.toFloat(), toTransform.height.toFloat())

        path.addRoundRect(
            rect,
            floatArrayOf(topLeft, topLeft, topRight, topRight, bottomRight, bottomRight, bottomLeft, bottomLeft),
            Path.Direction.CW
        )

        canvas.clipPath(path)
        canvas.drawBitmap(toTransform, 0f, 0f, paint)

        return roundedBitmap
    }

    companion object {
        private const val ID = "com.example.GlideRoundedCornersTransformation"
    }
}