我正在尝试制作一个扩展函数,以便在不同的类中使用它。我正在尝试创建它,但它不起作用。有人能解决这个问题吗。
这是我的分机号:
fun resize.toBitmap(image: Bitmap, maxWidth: Int, maxHeight: Int): Bitmap {
var image = image
return if (maxHeight > 0 && maxWidth > 0) {
val width = image.width
val height = image.height
val ratioBitmap = width.toFloat() / height.toFloat()
val ratioMax = maxWidth.toFloat() / maxHeight.toFloat()
var finalWidth = maxWidth
var finalHeight = maxHeight
if (ratioMax > ratioBitmap) {
finalWidth = (maxHeight.toFloat() * ratioBitmap).toInt()
} else {
finalHeight = (maxWidth.toFloat() / ratioBitmap).toInt()
}
image = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true)
image
} else {
image
}
这就是我试图达到它的方式:
var bitmap = Bitmap.createBitmap(drawingCacheBitmap)
bitmap = resize(bitmap, 200, 100)
试试这个
fun Bitmap.resizeImage(image: Bitmap, maxWidth: Int, maxHeight: Int): Bitmap {
val width = image.width
val height = image.height
val scaleWidth = maxWidth.toFloat() / width
val scaleHeight = maxHeight.toFloat() / height
val matrix = Matrix()
matrix.postScale(scaleWidth, scaleHeight)
// Create a New bitmap
val resizedBitmap = Bitmap.createBitmap(
image, 0, 0, width, height, matrix, false)
resizedBitmap.recycle()
return resizedBitmap
}
这样调用这个扩展函数,
bitmap = resizeImage(bitmap, 200, 100)