0

我正在尝试制作一个扩展函数以在不同的类中使用它。我正在尝试创建它,但它不起作用。任何人都可以解决这个问题。

这是我的扩展:

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)
4

1 回答 1

0

尝试这个

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)
于 2020-08-21T11:37:24.503 回答