在 Android 中 Matrix 实现图像的缩放和裁剪将 Glide 图像从 fitCenter 转换为 centerCrop

在 Android 中,Matrix 可以用来实现图像的缩放和裁剪逻辑。要将 Glide 图像从 fitCenter 转换为 centerCrop,需要通过 Matrix 计算变换逻辑。
以下是使用 Kotlin 实现的方法:
实现步骤
计算目标变换矩阵:根据目标宽高比,判断是否需要横向或纵向裁剪。
设置 Matrix:使用 Matrix 执行缩放和平移操作。
应用到 Glide:自定义一个 Glide 的 Transformation 类。
以下是完整的代码实现:

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

class FitCenterToCenterCropTransformation : BitmapTransformation() {
    override fun updateDiskCacheKey(messageDigest: MessageDigest) {
        messageDigest.update("fit_center_to_center_crop".toByteArray(Charsets.UTF_8))
    }

    override fun transform(
        pool: BitmapPool,
        toTransform: Bitmap,
        outWidth: Int,
        outHeight: Int
    ): Bitmap {
        val srcWidth = toTransform.width.toFloat()
        val srcHeight = toTransform.height.toFloat()
        val targetWidth = outWidth.toFloat()
        val targetHeight = outHeight.toFloat()

        val matrix = Matrix()

        // Calculate the scale
        val scale: Float
        val dx: Float
        val dy: Float

        if (srcWidth / srcHeight > targetWidth / targetHeight) {
            // Wider image, fit height and crop width
            scale = targetHeight / srcHeight
            dx = (targetWidth - srcWidth * scale) / 2
            dy = 0f
        } else {
            // Taller image, fit width and crop height
            scale = targetWidth / srcWidth
            dx = 0f
            dy = (targetHeight - srcHeight * scale) / 2
        }

        // Apply scale and translation
        matrix.setScale(scale, scale)
        matrix.postTranslate(dx, dy)

        // Create the transformed bitmap
        val transformedBitmap = pool.get(outWidth, outHeight, toTransform.config ?: Bitmap.Config.ARGB_8888)
        val canvas = Canvas(transformedBitmap)
        val paint = Paint(Paint.FILTER_BITMAP_FLAG)
        canvas.drawBitmap(toTransform, matrix, paint)

        return transformedBitmap
    }
}

使用方法
将自定义的 Transformation 应用到 Glide:

Glide.with(context)
    .load(imageUrl)
    .transform(FitCenterToCenterCropTransformation())
    .into(imageView)

解释
Matrix 的作用:通过 Matrix 调整图像的缩放和位置。
兼容性处理BitmapConfig 可能为空,所以在新建位图时要默认使用 ARGB_8888
Glide 的缓存updateDiskCacheKey 用于区分不同的变换操作,避免缓存冲突。
效果
该代码会将原本 fitCenter(全图适配但留黑边)的图片按比例裁剪,转换成 centerCrop(以中间为基准裁剪并充满视图)。

发布者:myrgd,转载请注明出处:https://www.object-c.cn/5067

Like (0)
Previous 2024年12月3日 下午12:23
Next 2024年12月3日 下午1:11

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

联系我们

在线咨询: QQ交谈

邮件:723923060@qq.com

关注微信