Bitmap和ImageView问题 - 图像宽度/高度问题

时间:2016-06-28 18:15:02

标签: android android-bitmap bitmapfactory

我需要显示存储在数据库中的图像,我遇到图像(位图)宽度/高度和ImageView的问题......

仅供测试 - 当我在项目的drawable中添加相同的图像时,我可以使用它:

使用:

Bitmap b = BitmapFactory.decodeResource(context.getResources(), R.drawable.menu_image);
BitmapDrawable bd = new BitmapDrawable(context.getResources(), b);
imageView.setImageDrawable(bd);

相同
imageView.setImageResource(R.drawable.menu_image);

以下无效,因为图片未调整大小:

imageView.setImageBitmap(image);

相同
imageView.setImageDrawable(new BitmapDrawable(context.getResources(), image));

使用以下方法构建图像:

public static Bitmap base64ToBitmap(String b64) {
    byte[] imageAsBytes = Base64.decode(b64.getBytes(), Base64.DEFAULT);
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inDensity =     context.getResources().getDisplayMetrics().densityDpi;
    options.inTargetDensity = context.getResources().getDisplayMetrics().densityDpi;
    Bitmap bitmap = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length, options);
    return bitmap;
}

图像原始尺寸为338x94。

676x188,当我使用项目的drawables目录中的图像时,这是图像大小。在这种情况下,这是我正在寻找的尺寸。我想快速解决方法是使用Bitmap.createScaledBitmap(),但我有几种不同的图像格式,我想使用imageView.setImageBitmap或imageView.setImageDrawable,就像我从项目的drawables目录中加载Bitmap一样。

1 个答案:

答案 0 :(得分:-1)

使用github

中的以下助手类
public class BitmapScaler
{
// scale and keep aspect ratio
public static Bitmap scaleToFitWidth(Bitmap b, int width)
{
    float factor = width / (float) b.getWidth();
    return Bitmap.createScaledBitmap(b, width, (int) (b.getHeight() * factor), true);
}


// scale and keep aspect ratio
public static Bitmap scaleToFitHeight(Bitmap b, int height)
{
    float factor = height / (float) b.getHeight();
    return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factor), height, true);
}


// scale and keep aspect ratio
public static Bitmap scaleToFill(Bitmap b, int width, int height)
{
    float factorH = height / (float) b.getWidth();
    float factorW = width / (float) b.getWidth();
    float factorToUse = (factorH > factorW) ? factorW : factorH;
    return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factorToUse),
            (int) (b.getHeight() * factorToUse), true);
}


    // scale and don't keep aspect ratio
    public static Bitmap strechToFill(Bitmap b, int width, int height)
     {
    float factorH = height / (float) b.getHeight();
    float factorW = width / (float) b.getWidth();
    return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factorW),
            (int) (b.getHeight() * factorH), true);
     }
  }