Glide實現圓角圖片,以及圓形圖片

m0_37777069發表於2020-09-27

Glide很常用,為了避免經常遷移專案導致重寫工具類,記錄下實現圓角圖片的功能以及圓形圖片的功能,
圓角圖片如下:

package com.yyb.mvvmlibrary.widget

import android.content.Context
import android.content.res.Resources
import android.graphics.*
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import java.security.MessageDigest

/**
 * author : 閆裕波
 * e-mail : yyb@zlhopesun.com
 * time   : 2020/8/7
 * desc   : 圓角圖示
 */
class GlideRoundTransform @JvmOverloads constructor(
    context: Context?,
    dp: Int = 4
) : BitmapTransformation() {
    override fun transform(
        pool: BitmapPool,
        toTransform: Bitmap,
        outWidth: Int,
        outHeight: Int
    ): Bitmap {
        return roundCrop(pool, toTransform)!!
    }

    override fun updateDiskCacheKey(messageDigest: MessageDigest) {}

    companion object {
        private var radius = 0f
        private fun roundCrop(pool: BitmapPool, source: Bitmap?): Bitmap? {
            if (source == null) return null
            val result =
                pool[source.width, source.height, Bitmap.Config.ARGB_8888]
            val canvas = Canvas(result)
            val paint = Paint()
            paint.shader = BitmapShader(
                source,
                Shader.TileMode.CLAMP,

                Shader.TileMode.CLAMP
            )
            paint.isAntiAlias = true
            val rectF = RectF(
                0f, 0f, source.width.toFloat(), source.height
                    .toFloat()
            )
            canvas.drawRoundRect(
                rectF,
                radius,
                radius,
                paint
            )
            return result
        }
    }
    /**
     * 建構函式
     *
     * @param context Context
     * @param dp 圓角半徑
     */
    /**
     * 建構函式 預設圓角半徑 4dp
     *
     * @param context Context
     */
    init {
        radius =
            Resources.getSystem().displayMetrics.density * dp
    }
}

工具類如下:

//圓形圖片
fun circleImageUrl(view: ImageView, url: String) {
    Glide.with(view.context)
        .load(url)
        .apply(RequestOptions.bitmapTransform(CircleCrop()))
        .transition(DrawableTransitionOptions.withCrossFade(500))
        .into(view)
}
//圓角圖片
fun roundedCornerImagUrl(view:ImageView,url:String,radiis:Int){
    Glide.with(view.context)
        .load(url)
        .transform(CenterCrop(),GlideRoundTransform(view.context,radiis))
        .transition(DrawableTransitionOptions.withCrossFade(500))
        .into(view)

}

相關文章