Android的大小调整位图保持宽高比 [英] Android resize bitmap keeping aspect ratio
本文介绍了Android的大小调整位图保持宽高比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个自定义视图(1066 x 738),和我传递一个位图图像(720x343)。我希望以位图以适应自定义视图不超出界父。
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.
我要实现的是这样的:
我应该如何计算位图大小?
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:
推荐答案
您应该尝试使用内置的 ScaleToFit.CENTER
的转换矩阵。例如:
You should try using a transformation matrix built for ScaleToFit.CENTER
. For example:
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);
这篇关于Android的大小调整位图保持宽高比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文