【问题标题】:Efficient Bitmaps高效位图
【发布时间】:2015-05-17 12:14:19
【问题描述】:

最近,在尝试在 imageView 中加载图像时,我遇到了“堆内存不足”错误。于是我上网查了一下,找到了优化图片的方法。

我期待找到优化位图的最佳方法。

目前,我有一个 ImageView,其高度为 200dp,宽度为“match_parent”。基本上它水平填充屏幕并垂直占用 200dp。

我正在尝试实现类似于此图像的目标。

这是我这样做的总体计划。

1) 为 1 行创建布局(ImageView、TextView、文本后面的黑色半透明条)

2) 使用 RecyclerView 并膨胀数据

目前我卡在第 1 步(对代码不满意)。

我所做的是为行创建一个 XML 布局。

<RelativeLayout
android:id="@+id/layout_adventure_fragment"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="200dp">

<ImageView
    android:id="@+id/imageView_adventure_home_screen_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<TextView
    android:background="@drawable/textview_background_gradient"
    android:layout_alignParentBottom="true"
    android:paddingBottom="10dp"
    android:paddingTop="10dp"
    android:paddingLeft="15dp"
    android:textColor="#FFFFFF"
    android:textSize="25sp"
    android:id="@+id/textView_adventure_name_home_screen_fragment"
    android:layout_width="match_parent"
    android:layout_height="55dp"
    android:text="Demo Text"/>

</RelativeLayout>

稍后我将根据排版指南调整 TextView。

好的,所以基本上 ImageView 是 200dp 高。 为了压缩我的图像,我使用了 Android 培训页面上的指南,该指南使用 inSampleSize 并在 AsyncTask 中加载图像。

为了计算所需的高度,我使用了一些我不确定它是否正确的方法。因为我只关心高度压缩图像,所以我只传递了高度来计算 inSampleSize。

    DisplayMetrics disp = getApplicationContext().getResources().getDisplayMetrics();
    int density = disp.densityDpi;
    width = disp.widthPixels;
    height = (int)((float)(200.0/160.0) * (float)density);

    Bitmap b =decodeSampledBitmapFromResource(getResources(),R.drawable.shake,height);
    loadBitmap(R.drawable.shake,iV);

最后,我从最终位图中提取了所需宽度和高度的缩略图,以向用户显示填充 imageView 的图像,而不是仅在中间有边距。

imageView.setImageBitmap(ThumbnailUtils.extractThumbnail(bitmap,width,height));

完整代码可以在这里找到:http://pastebin.com/mhKi1sKd

优化 imageView 的最佳方法是什么,以便在 RecyclerView 中显示多个图像时,堆内存不会被填满,并且如果我的程序中有不必要的代码只会占用处理和宝贵的时间?

这是我到现在为止的成就。

【问题讨论】:

    标签: android optimization bitmap


    【解决方案1】:

    看看Picasso 库。

    处理了 Android 上图像加载的许多常见陷阱 由毕加索自动完成:

    Handling ImageView recycling and download cancelation in an adapter.
    Complex image transformations with minimal memory use.
    Automatic memory and disk caching.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      相关资源
      最近更新 更多