问题描述
我试图制作一个扩展函数以在其他类中使用它。我正在尝试创建它,但是它不起作用。谁能解决这个问题。
这是我的扩展名:
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,width,height,matrix,false)
resizedBitmap.recycle()
return resizedBitmap
}
并像这样调用此扩展功能,
bitmap = resizeImage(bitmap,200,100)