Android kotlin - 调整位图大小的基本数学问题



我得到了这个代码:

var newheight = 1000
if(myBitmap.height > newheight){
var aspect = myBitmap.height / myBitmap.width
Log.d("letsSee", "width: " + myBitmap.width + " height: " + myBitmap.height) // letsSee: width: 2592 height: 1458
var newwidth = newheight * aspect
Log.d("letsSee", "newwidth: " + newwidth + " aspect: " + aspect) // newwidth: 0 aspect: 0
myBitmap = createScaledBitmap (myBitmap, newwidth, newheight,false)
}

应用程序以这种方式崩溃,这是怎么回事?我还尝试添加.toInt()

var newwidth = newheight * aspect.toInt()
myBitmap = createScaledBitmap (myBitmap, newwidth.toInt(), newheight,false)

..

这是一个舍入错误:

var aspect = myBitmap.height / myBitmap.width

当您除以 1458/2592 时,它是 0.5625,但两个变量都intaspect变量也是如此。结果,它向下舍入为 0。

您需要将表达式计算为 floats(将至少 1 个变量强制转换为 float 以隐式更改结果类型(:

var aspect = myBitmap.height / myBitmap.width.toFloat()

你的方面现在应该在 0.5625 左右。然后在计算宽度(以像素为单位(时向下投射到int

var newwidth = (newheight * aspect).toInt()

在行中var aspect = myBitmap.height / myBitmap.width

在 kotlin 中,当您将整数除以整数时,结果将四舍五入为整数。

首先,根据您的用例,宽高>宽度/高度

此外,当您以整数形式获取结果时,如果结果为 0.5,则aspect的值将为 ZERO,因为它是一个整数。应用程序崩溃,因为新宽度变为零。

请将行更改为

val aspect = myBitmap.width.toFloat() / myBitmap.height.toFloat()

并在调用createScaledBitmap时使用newwidth.toInt().

附言请不要介意我的语法。

最新更新