ImageView尺寸

时间:2015-12-26 16:35:25

标签: android android-layout bitmap android-image dimensions

我有以下情况

我内部有created_atImageView

问题就是那个

  • 我不知道位图的尺寸(不是物理尺寸,屏幕尺寸)

  • 我需要Bitmap不要大于屏幕上的ImageView

Bitmap的背景在下方快照上有黑色。

1 个答案:

答案 0 :(得分:0)

通过在其xml文件中的imageView标记上将layout_width和layout_height设置为wrap_content,可以确保图像视图不大于位图。

您还可以使用其scaleType来影响应如何操作图像以适合imageView。

您还可以访问位图的宽度/高度属性以获取其尺寸。

EDIT ::

您可以将位图转换为byte []并使用以下帮助程序调整其大小:

/**
 * Resize an image to a specified width and height.
 * @param targetWidth The width to resize to.
 * @param targetHeight The height to resize to.
 * @return The resized image as a Bitmap.
 * */
public static Bitmap resizeImage(byte[] imageData, int targetWidth, int targetHeight) {
    BitmapFactory.Options options = new BitmapFactory.Options();

    options.inSampleSize = calculateInSampleSize(options, targetWidth, targetHeight);
    options.inJustDecodeBounds = false;

    Bitmap reducedBitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length, options);
    return Bitmap.createScaledBitmap(reducedBitmap, targetWidth, targetHeight, false);
}

private static int calculateInSampleSize(BitmapFactory.Options options, int requestedWidth, int requestedHeight) {
    // Get the image's raw dimensions
    final int rawHeight = options.outHeight;
    final int rawWidth = options.outWidth;

    int inSampleSize = 1;
    if (rawHeight > requestedHeight || rawWidth > requestedWidth) {
        final int halfHeight = rawHeight / 2;
        final int halfWidth = rawWidth / 2;

        /*
        * Calculate the largest inSampleSize value that is a power of 2 and keeps both
        * height and width larger than their requested counterparts respectively.
        * */
        while ((halfHeight/inSampleSize) > requestedHeight && (halfWidth/inSampleSize) > requestedWidth) {
            inSampleSize *= 2;
        }
    }
    return inSampleSize;
}