先引入如下類1:
import android.content.Context
import android.graphics.Bitmap
import android.renderscript.Allocation
import android.renderscript.Element
import android.renderscript.RenderScript
import android.renderscript.ScriptIntrinsicBlur
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.CenterCrop
class GlideBlurTransformation(private val context: Context) : CenterCrop() {
override fun transform(
pool: BitmapPool,
toTransform: Bitmap,
outWidth: Int,
outHeight: Int
): Bitmap {
val bitmap = super.transform(pool, toTransform, outWidth, outHeight)
return blurBitmap(context, bitmap, 25f, outWidth / 2, outHeight / 2)
}
private fun blurBitmap(
context: Context?,
image: Bitmap?,
blurRadius: Float,
outWidth: Int,
outHeight: Int
): Bitmap {
// 将縮小後的圖檔做為預渲染的圖檔
val inputBitmap = Bitmap.createScaledBitmap(image!!, outWidth, outHeight, false)
// 建立一張渲染後的輸出圖檔
val outputBitmap = Bitmap.createBitmap(inputBitmap)
// 建立RenderScript核心對象
val rs = RenderScript.create(context)
// 建立一個模糊效果的RenderScript的工具對象
val blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs))
// 由于RenderScript并沒有使用VM來配置設定記憶體,是以需要使用Allocation類來建立和配置設定記憶體空間
// 建立Allocation對象的時候其實記憶體是空的,需要使用copyTo()将資料填充進去
val tmpIn = Allocation.createFromBitmap(rs, inputBitmap)
val tmpOut = Allocation.createFromBitmap(rs, outputBitmap)
// 設定渲染的模糊程度, 25f是最大模糊度
blurScript.setRadius(blurRadius)
// 設定blurScript對象的輸入記憶體
blurScript.setInput(tmpIn)
// 将輸出資料儲存到輸出記憶體中
blurScript.forEach(tmpOut)
// 将資料填充到Allocation中
tmpOut.copyTo(outputBitmap)
return outputBitmap
}
}
然後這樣使用:
- Glide4.x 圖檔高斯模糊 ↩︎