Android保持宽高比调整位图大小

17

我有一个自定义视图(1066 x 738),并且我正在传递一个位图图像(720x343)。我希望将位图缩放以适应自定义视图,而不超出父级的边界。

enter image description here

我想要实现这样的效果:

enter image description here

如何计算位图大小?

如何计算新的宽度/高度:

    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);
    }

但我所做的只有这个结果:

在此输入图片描述


你可以在自定义视图的XML中添加scaleType标志。http://developer.android.com/reference/android/widget/ImageView.ScaleType.html - Brett Haines
这不是一个imageView! - Zbarcea Christian
啊,我(错误地)假设你的自定义视图扩展了ImageView...是我的错。 - Brett Haines
1个回答

67

你应该尝试使用为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);

1
对我没用。我尝试使用这个来减小图像大小、分辨率,但没有起作用。 - Narendra Singh
1
@DroidWormNarendra,您可以调用Bitmap.createScaledBitmap(out, reqWidth, reqHeight, false); 这将缩小图像的尺寸。 - zionpi
@matiash,请看一下这个问题 http://stackoverflow.com/questions/42927337/scaling-bitmaps-of-huge-images-from-url-into-image-view-according-to-device-reso - user2028
适用于我。 - Rakesh Yadav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接