在网格视图中延迟加载图像,解码来自SD卡的图像路径

时间:2013-02-01 17:02:07

标签: android performance android-imageview

嗨我有一组SD卡上的图像路径,所有图像都很大,如1024 * 768像素。

我需要在相对缩小的图像的网格视图中显示所有这些图像。我需要先显示网格视图,然后加载生成的缩小图像。我怎样才能做到这一点。

现在是:

获取所有图像路径,

File imgFile = new File(pathToImageOnSD);
            if (imgFile.exists()) {

                BitmapFactory.Options op = new BitmapFactory.Options();
                op.inSampleSize = 4;

                Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

                item.bitmap = myBitmap;
                imageview.setImageBitmap(myBitmap);

            }

我正在为每个图像路径执行此操作,并以内存错误结束。有些库可以从网址加载图片,但我需要一个类似的工具来加载SD卡上的本地图像。

编辑:

public Bitmap loadBitmapFromPath(File f) {
            // decodes image and scales it to reduce memory consumption

            try {
                // decode image size
                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                FileInputStream stream1 = new FileInputStream(f);
                BitmapFactory.decodeStream(stream1, null, o);
                stream1.close();

                // Find the correct scale value. It should be the power of 2.
                final int REQUIRED_SIZE = 70;
                int width_tmp = o.outWidth, height_tmp = o.outHeight;
                int scale = 1;
                while (true) {
                    if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
                        break;
                    width_tmp /= 2;
                    height_tmp /= 2;
                    scale *= 2;
                }

                if (scale >= 2) {
                    scale /= 2;
                }

                // decode with inSampleSize
                BitmapFactory.Options o2 = new BitmapFactory.Options();
                o2.inSampleSize = scale;
                FileInputStream stream2 = new FileInputStream(f);
                Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
                stream2.close();
                return bitmap;
            } catch (FileNotFoundException e) {
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

我使用上面的方法缩小位图,它工作得很好。但我的问题是当我滚动网格时,视图被重绘并且流程不流畅,如何缓存这些位图以及如何延迟加载它们以便我不需要等待视图完全填充。

1 个答案:

答案 0 :(得分:1)

要节省内存,请始终将位图解码为您计划显示的相同大小。对于这个问题,官方文档是你最好的朋友。下载BitmapFun项目以确切了解如何正确执行此操作。 https://developer.android.com/training/displaying-bitmaps/index.html