网上关于BitmapTransformation也没啥好的例子,我下了份源码,抄抄改改,不知道改的对不对,反正效果实现了,一开始我直接返回new Bitmap,看源码都不这么用,源码都是从BitmapPool去拿的Bitmap了,不知道是不是要复用,反正抄就完事了。最后效果实现了
import android.graphics.Bitmap
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import java.security.MessageDigest
class GlideBitmapTransformation : BitmapTransformation() {
private val ID = "com.bumptech.glide.transformations.GlideBitmapTransformation"
private val ID_BYTES: ByteArray = ID.toByteArray(charset(STRING_CHARSET_NAME))
override fun updateDiskCacheKey(messageDigest: MessageDigest) {
messageDigest.update(ID_BYTES)
}
override fun equals(o: Any?): Boolean {
return o is GlideBitmapTransformation
}
override fun hashCode(): Int {
return ID.hashCode()
}
override fun transform(
pool: BitmapPool,
toTransform: Bitmap,
outWidth: Int,
outHeight: Int
): Bitmap {
return TransformationUtil.centerScale(pool, toTransform, outWidth, outHeight)
}
}
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.TransformationUtils
import java.util.concurrent.locks.ReentrantLock
object TransformationUtil {
private val BITMAP_DRAWABLE_LOCK = ReentrantLock()
private val DEFAULT_PAINT = Paint(TransformationUtils.PAINT_FLAGS)
fun centerScale(
pool: BitmapPool, toTransform: Bitmap, outWidth: Int, outHeight: Int
): Bitmap {
if (toTransform.getWidth() == outWidth && toTransform.getHeight() == outHeight) {
return toTransform
}
val config = getNonNullConfig(toTransform)
val toReuse = pool[outWidth, outHeight, config]
val width: Int = toTransform.getWidth()
val height: Int = toTransform.getHeight()
val scaleWidth: Float = outWidth.toFloat() / width
val scaleHeight: Float = outHeight.toFloat() / height
val matrix = Matrix()
val dx: Float
val dy: Float
if (scaleWidth > scaleHeight) {
dx = (outWidth - toTransform.getWidth() * scaleHeight) * 0.5f
dy = 0f
matrix.postScale(scaleHeight, scaleHeight)
} else {
dx = 0f
dy = (outHeight - toTransform.getHeight() * scaleWidth) * 0.5f
matrix.postScale(scaleWidth, scaleWidth)
}
matrix.postTranslate(dx, dy)
applyMatrix(toTransform, toReuse, matrix)
return toReuse
}
private fun getNonNullConfig(bitmap: Bitmap): Bitmap.Config? {
return if (bitmap.config != null) bitmap.config else Bitmap.Config.ARGB_8888
}
private fun applyMatrix(
inBitmap: Bitmap, targetBitmap: Bitmap, matrix: Matrix
) {
BITMAP_DRAWABLE_LOCK.lock()
try {
val canvas = Canvas(targetBitmap)
canvas.drawBitmap(inBitmap, matrix, DEFAULT_PAINT)
clear(canvas)
} finally {
BITMAP_DRAWABLE_LOCK.unlock()
}
}
private fun clear(canvas: Canvas) {
canvas.setBitmap(null)
}
}
Glide.with(holder.itemView)
.load(data.filePath)
.transform(GlideBitmapTransformation())
.into(holder.imageView)
网友评论