Coil居中裁剪Transform

252 阅读1分钟

发现Coil没有自带CenterCropTransform,于是自己写了一个,类似于ImageView的CenterCrop,代码如下:

class CenterCropTransform : Transformation {
    override fun key(): String = CenterCropTransform::class.java.name

    override suspend fun transform(pool: BitmapPool, input: Bitmap, size: Size): Bitmap {
        val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)

        val outputWidth: Int
        val outputHeight: Int
        when (size) {
            is PixelSize -> {
                val multiplier = DecodeUtils.computeSizeMultiplier(
                    srcWidth = input.width,
                    srcHeight = input.height,
                    dstWidth = size.width,
                    dstHeight = size.height,
                    scale = Scale.FILL
                )
                outputWidth = (size.width / multiplier).roundToInt()
                outputHeight = (size.height / multiplier).roundToInt()
            }
            is OriginalSize -> {
                outputWidth = input.width
                outputHeight = input.height
            }
        }

        val output = pool.get(outputWidth, outputHeight, input.config ?: Bitmap.Config.ARGB_8888)
        output.applyCanvas {
            drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)

            val matrix = Matrix()
            matrix.setTranslate((outputWidth - input.width) / 2f, (outputHeight - input.height) / 2f)
            val shader = BitmapShader(input, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
            shader.setLocalMatrix(matrix)
            paint.shader = shader

            val rect = if (width > height) {
                RectF((width - height) / 2f, 0f, (width - height) / 2f + height, height.toFloat())
            } else {
                RectF(0f, (height - width) / 2f, width.toFloat(), (height - width) / 2f + width)
            }
            val path = Path().apply { addRect(rect, Path.Direction.CW) }
            drawPath(path, paint)
        }

        return output
    }
}