[英]Efficient Bitmaps
最近,在尝试在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中显示多个图像时,堆内存不会满,并且程序中是否有不必要的代码仅占用处理时间和宝贵时间?
这是我到目前为止所取得的成就。
看看Picasso
图书馆。
毕加索会自动处理Android上许多常见的图片加载陷阱:
Handling ImageView recycling and download cancelation in an adapter. Complex image transformations with minimal memory use. Automatic memory and disk caching.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.