在 Coil 中,BlurTransformation 是用于给加载的图片添加模糊效果的转换器。它可以轻松实现图片的高斯模糊效果,无需手动编写复杂的模糊算法。

基本使用方法

BlurTransformation 位于 coil-transformations 模块中,需要先添加依赖:

// 基础依赖
implementation("io.coil-kt:coil:2.4.0")
// 转换器依赖(包含 BlurTransformation)
implementation("io.coil-kt:coil-transformations:2.4.0")

使用示例:

import coil.load
import coil.transform.BlurTransformation

// 加载图片并添加模糊效果
imageView.load("https://picsum.photos/600/400") {
    // 添加模糊转换器,radius 为模糊半径(值越大越模糊)
    transformations(BlurTransformation(context = context, radius = 15f))
    // 可选:添加其他转换器(如圆形裁剪)
    // transformations(BlurTransformation(context, 15f), CircleCropTransformation())
}

参数说明

BlurTransformation 的构造函数主要参数:

  • context: 上下文对象
  • radius: 模糊半径(默认 10f,范围建议 0f-25f,值越大模糊效果越强)
  • sampling: 采样率(默认 1f,值越大图片会先缩小再模糊,性能更好但清晰度降低)

例如,兼顾性能和效果的配置:

transformations(BlurTransformation(
    context = context,
    radius = 20f,    // 较强的模糊效果
    sampling = 2f    // 先缩小一半再模糊,提升性能
))

注意事项

  1. 性能考量

    • 模糊半径越大,性能消耗越高,建议根据实际场景调整(通常 10f-20f 效果较好)
    • 增大 sampling 值(如 2f 或 4f)可以显著提升性能,适合对清晰度要求不高的场景(如背景模糊)
  2. 版本兼容

    • BlurTransformation 内部使用了 RenderScript 或 BitmapShader 实现,兼容 API 14+
    • 在 API 28+ 上会优先使用更高效的 RenderScript 实现
  3. 与其他转换器结合
    可以和其他转换器(如 CircleCropTransformationRoundedCornersTransformation 等)一起使用,实现复合效果:

import coil.transform.CircleCropTransformation
import coil.transform.RoundedCornersTransformation

transformations(
    BlurTransformation(context, 15f),
    RoundedCornersTransformation(16.dp.toPx()) // 同时添加圆角
)

通过 BlurTransformation,可以在 Coil 加载图片时轻松实现模糊效果,无需手动处理 bitmap,极大简化了图片模糊的实现逻辑。

转自:Coil 中 BlurTransformation - 豆包

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐