如何在Kotlin中创建扩展功能以调整图像大小?

问题描述

我试图制作一个扩展函数以在其他类中使用它。我正在尝试创建它,但是它不起作用。谁能解决这个问题。

这是我的扩展名:

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)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...