gpt4 book ai didi

android - 将位图的大小调整为固定值但不更改纵横比

转载 作者:可可西里 更新时间:2023-11-01 18:49:29 26 4
gpt4 key购买 nike

我正在寻找以下问题的解决方案:如何将 Bitmap 的大小更改为固定大小(例如 512x128)。必须保留位图内容的纵横比。

我觉得应该是这样的:

  • 创建一个空的 512x128 位图

  • 在保持宽高比的情况下缩小原始位图以适应 512x128 像素

  • 复制缩放到空位图中(居中)

实现此目标的最简单方法是什么?

所有这一切的原因是,当图像的纵横比与其他图像不同时,GridView 会弄乱布局。这是一个屏幕截图(除了最后一张之外的所有图像的纵横比均为 4:1):

screenshot

最佳答案

试试这个,计算比率,然后重新缩放。

private Bitmap scaleBitmap(Bitmap bm) {
int width = bm.getWidth();
int height = bm.getHeight();

Log.v("Pictures", "Width and height are " + width + "--" + height);

if (width > height) {
// landscape
float ratio = (float) width / maxWidth;
width = maxWidth;
height = (int)(height / ratio);
} else if (height > width) {
// portrait
float ratio = (float) height / maxHeight;
height = maxHeight;
width = (int)(width / ratio);
} else {
// square
height = maxHeight;
width = maxWidth;
}

Log.v("Pictures", "after scaling Width and height are " + width + "--" + height);

bm = Bitmap.createScaledBitmap(bm, width, height, true);
return bm;
}

关于android - 将位图的大小调整为固定值但不更改纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15124179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com