我想避免Out of Memory Exception使用最佳实践在android中加载图像位图

时间:2014-02-25 06:46:50

标签: android bitmap imageview bitmapimage

我想使用教程“有效加载大位图”中描述的步骤。但我对如何确定要在任何设备中显示的图像的适当高度和宽度感到困惑。在教程中,所需的高度和宽度是硬编码的。我希望动态地为任何设备提供适当的所需高度和宽度。怎么做......

...谢谢

教程中的步骤如下 获取图像高度和宽度

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;  

计算用于解码图像位图的样本大小

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

if (height > reqHeight || width > reqWidth) {

    final int halfHeight = height / 2;
    final int halfWidth = width / 2;

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

return inSampleSize;
}

2 个答案:

答案 0 :(得分:0)

请尝试以下操作:

final ImageView myImage = (ImageView) view
        .findViewById(R.id.test_image);
final ViewParent parent = myImage.getParent();

if (parent instanceof ViewGroup) {
    ((ViewGroup) parent).getViewTreeObserver()
            .addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

                @Override
                public void onGlobalLayout() {
                    ((ViewGroup) parent).getViewTreeObserver()
                            .removeGlobalOnLayoutListener(this);

                    int reqWidth = ((ViewGroup) parent).getWidth();
                    int reqHeight = ((ViewGroup) parent).getHeight();

                    // Load image...
                }
            });
}

答案 1 :(得分:0)

您也可以声明标签,即

android:largeHeap="true"

在您的清单中的<application>标记内。

示例: -

<application 

    android:label="@string/app_name" 
    android:icon="@drawable/icon"
    android:largeHeap="true"
    android:description="@string/app_description"
    android:allowBackup="true"
    >