gpt4 book ai didi

android - 查看带有大量图像的分页,它甚至可以工作吗?

转载 作者:行者123 更新时间:2023-11-30 04:16:01 25 4
gpt4 key购买 nike

内存问题

所以我正在编写一个应用程序,它应该能够翻阅顶部有一个 640 x 480 大图像和 3 个图像的详细 View ,这些图像是延迟加载的图库的一部分。遵循谷歌设计指南,这是他们建议做的事情。在它因内存不足而崩溃之前,我可以翻阅 12 - 13 个 fragment 。我认为这个问题有几个罪魁祸首。

1.) 我正在使用 FragmentStatePager。当内存成为问题时,这不应该破坏未被查看的 fragment 吗?这没有发生。我以为是自动的我必须做什么才能做到这一点?这可能与我如何实现 fragment 有关吗?我在 onCreateView 中完成所有 Activity 配置。为了彻底起见,我已经包含了它的来源。这里是纯 Vanilla :

public static class MyAdapter extends FragmentStatePagerAdapter {


public MyAdapter(FragmentManager fm) {
super(fm);
}

@Override
public int getCount() {
return NUM_ITEMS;
}

@Override
public Fragment getItem(int position) {
return InventoryDetailFragment.newInstance(position);
}
}

2.) 我有一个方法试图计算出需要下载的图像的大小而不将它放在内存中。然后在下载到所需大小的同时压缩图像。这没有成功实现。但我不确定出了什么问题。

private Bitmap downloadBitmap(String url, int width, int height) {
Bitmap bitmap = null;
int scale = 1;
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
bitmap = BitmapFactory.decodeStream((InputStream)new URL (url).getContent(), null, options);

if (options.outHeight > height || options.outWidth > width) {
scale = (int) Math.max(((options.outHeight)/ height), ((options.outWidth)/ width)); }

BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeStream((InputStream)new URL (url).getContent(), null, o2);
cache.put(url, new SoftReference<Bitmap>(bitmap));


} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Error e){
Log.d("TEST", "Garbage Collector called!");
System.gc();
}
return bitmap;
}

我已经尝试了所有我知道如何做的事情,但这超出了我对 Android/Java 的微薄掌握。请帮忙!谢谢!

最佳答案

您需要更改一些内容:

  1. 这是一个可怕的想法:BitmapFactory.decodeStream((InputStream)new URL (url).getContent(), null, options); 你从网络上获取图像每次执行此操作时(所以在您发布的代码中 两次)。相反,您需要下载图像并将其缓存在本地。

  2. 向您的 fragment 添加逻辑,以便在 fragment 分离后立即对位图调用 recycle()。添加逻辑以在附加 fragment 时始终重新加载图像(从缓存中)。

  3. 最后,您的inSampleSize 计算有误。 inSampleSize 应该是一个 2 的幂的值,例如1,2,4,8。您可以使用对数或简单的二进制逻辑来获得正确的结果,这就是我使用的方法,它始终会至少使用 2 进行下采样(只有在您知道图像太大时才调用它):

-

int ratio =  (int) Math.max((height/options.outHeight), ( width/options.outWidth); //notice that they're flipped     
for (int powerOfTwo = 64; powerOfTwo >=2; powerOfTwo = powerOfTwo >> 1 ) { //find the biggest power of two that represents the ratio
if ((ratio & powerOfTwo) > 0) {
return powerOfTwo;
}
}

关于android - 查看带有大量图像的分页,它甚至可以工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10012548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com