Android调整位图大小保持纵横比
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24961797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android resize bitmap keeping aspect ratio
提问by Zbarcea Christian
I have a custom view (1066 x 738), and I am passing a bitmap image (720x343). I want to scale the bitmap to fit in the custom view without exceeding the bound of the parent.
我有一个自定义视图 (1066 x 738),我正在传递一个位图图像 (720x343)。我想缩放位图以适应自定义视图而不超出父级的边界。
I want to achieve something like this:
我想实现这样的目标:
How should I calculate the bitmap size?
我应该如何计算位图大小?
How I calculate the new width/height:
我如何计算新的宽度/高度:
public static Bitmap getScaledBitmap(Bitmap b, int reqWidth, int reqHeight)
{
int bWidth = b.getWidth();
int bHeight = b.getHeight();
int nWidth = reqWidth;
int nHeight = reqHeight;
float parentRatio = (float) reqHeight / reqWidth;
nHeight = bHeight;
nWidth = (int) (reqWidth * parentRatio);
return Bitmap.createScaledBitmap(b, nWidth, nHeight, true);
}
But all I am achieving is this:
但我所取得的成就是:
回答by matiash
You should try using a transformation matrix built for ScaleToFit.CENTER
. For example:
您应该尝试使用为ScaleToFit.CENTER
. 例如:
Matrix m = new Matrix();
m.setRectToRect(new RectF(0, 0, b.getWidth(), b.getHeight()), new RectF(0, 0, reqWidth, reqHeight), Matrix.ScaleToFit.CENTER);
return Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), m, true);