【发布时间】:2020-05-26 17:10:52
【问题描述】:
我正在尝试画一张背面有图案的扑克牌。我有 1 个尺寸的可绘制对象并以编程方式缩放这些可绘制对象。
它在我的平板电脑(Pixel C,运行 Android 8.1)上完美运行,但卡背面的设计在我的手机(Pixel 3a,运行 Android 10)上无法正常缩放。在 Pixel 3a 上,图像比预期的要大得多,并且不在卡的背面居中。此外,卡片本身似乎可以正常缩放,而不是放在上面的设计。
编辑:这似乎是操作系统级别的问题。我有一个使用 API 29(Android 10,与我的物理手机相同)的模拟 Pixel 3a,它看起来与下面我的物理手机的屏幕截图相同。但是,当我使用 API 27(Android 8.1)创建 Pixel 3a 模拟器时,它看起来就像在运行相同操作系统的平板电脑上一样。任何想法为什么?似乎这是操作系统级别的错误,但我不确定哪个函数包含该问题,或者如何准确重现它。
编辑 2:看起来 API 27 是最后一个显示我希望看到的内容。我尝试了使用 API 28、29 和 R 的模拟器,所有模拟器显示的图像都比我预期的要大得多。
这是我正在运行的代码:
private fun createImageInImageCenter(context: Context, backgroundBitmap: Bitmap, bitmapToDrawInTheCenter : Bitmap) : Drawable {
// Figure out width / height
val resultBitmap = Bitmap.createBitmap(
backgroundBitmap.width,
backgroundBitmap.height,
backgroundBitmap.config
)
val scaledCenter = scaleImage(bitmapToDrawInTheCenter, backgroundBitmap.height /2,
backgroundBitmap.width / 2)
val canvas = Canvas(resultBitmap)
// Draw background
canvas.drawBitmap(backgroundBitmap, Matrix(), Paint())
// Draw design centered on top
canvas.drawBitmap(
scaledCenter,
((backgroundBitmap.width - scaledCenter.width) / 2).toFloat(), // left
((backgroundBitmap.height - scaledCenter.height) / 2).toFloat(), // top
Paint()
)
return BitmapDrawable(context.resources, resultBitmap)
}
private fun scaleImage (image: Bitmap, maxHeight: Int, maxWidth: Int = -1) : Bitmap {
var ratio = 1f
if(maxWidth > 0 && image.width > maxWidth)
ratio = maxWidth.toFloat() / image.width
if(maxHeight > 0 && (image.height * ratio).roundToInt() > maxHeight)
ratio = maxHeight.toFloat() / image.height
val sizeX = (image.width * ratio).roundToInt()
val sizeY = (image.height * ratio).roundToInt()
return Bitmap.createScaledBitmap(image, sizeX, sizeY, false)
}
fun drawCard() {
// Resize the card itself
val cardHeight = context.resources.getDimension(R.dimen.card_max_height)
val back = scaleImage(context.getDrawable(R.drawable.card_black)!!, cardHeight.toInt())
// Resize the design on the card
val image = scaleImage(context.getDrawable(R.drawable.triforce)!!, back.height / 2, back.width / 2)
pic = createImageInImageCenter(context, back, image)
}
注意:我不知道为什么图片这么大,或者如何在这里缩放它们。
【问题讨论】:
标签: android kotlin bitmap scale