2

在设备中使用高分辨率图像时出现问题。

 imageview a;
InputStream ims = getAssets().open("sam.png");//sam.png=520*1400 device=320*480 or 480*800
Drawable d=Drawable.createFromStream(ims, null);
a.setLayoutParams(new        LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
a.setImageDrawable(d);

通过使用上面的代码图像在下一个内容的顶部和底部留下空间,或者如果我通过提供固定像素来缩小图像,它会在其大小上获得模糊图像。无论如何要解决这个问题?

4

2 回答 2

0

尝试创建Bitmap而不是Drawable

Bitmap bmp = BitmapFactory.decodeStream(ims);
a.setImageBitmap(bmp);

看起来Android根据屏幕密度做了一些可绘制的技巧。

于 2012-08-14T09:20:11.700 回答
0

希望以下解决方案有所帮助。您可以制作固定大小的 imageView 并将该 imageView 的宽度和高度传递给calculateInSampleSize方法。根据图像大小,它将决定是否对图像进行下采样。

public Bitmap getBitmap(Context context, final String imagePath)
{
    AssetManager assetManager = context.getAssets();
    InputStream inputStream = null;
    Bitmap bitmap = null;
    try
    {
        inputStream = assetManager.open(imagePath);         

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = true;
        options.inJustDecodeBounds = true;

        // First decode with inJustDecodeBounds=true to check dimensions
        bitmap = BitmapFactory.decodeStream(inputStream);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, requiredWidth, requiredHeight);

        options.inJustDecodeBounds = false;

        bitmap = BitmapFactory.decodeStream(inputStream);
    }
    catch(Exception exception) 
    {
        exception.printStackTrace();
        bitmap = null;
    }

    return bitmap;
}


public int calculateInSampleSize(BitmapFactory.Options options, final int requiredWidth, final int requiredHeight) 
{
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if(height > requiredHeight || width > requiredWidth) 
    {
        if(width > height) 
        {
            inSampleSize = Math.round((float)height / (float)requiredHeight);
        } 
        else 
        {
            inSampleSize = Math.round((float)width / (float)requiredWidth);
        }
    }

    return inSampleSize;
}
于 2012-08-14T09:44:05.270 回答