如果我预加载某些图像,这对我的应用程序是有利的。正如官方文档中所写,我在 AsyncTask 中正确地执行了此操作。但是我对何时设置它们有疑问。
我将展示代码 fragment 。请注意,它是简化的(它们在我的真实代码中的互操作性更好,它检查空值等)。
让我们先看看原始(非预加载)版本:
<ImageView
android:id="@+id/imageViewMyGraphicalImageElement"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="centerCrop"
android:src="@drawable/my_graphical_element" >
</ImageView>
预加载版本具有以下 XML(请注意缺少 src 属性):
<ImageView
android:id="@+id/imageViewMyGraphicalImageElement"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="centerCrop">
</ImageView>
还有一段预加载代码:
sBitmap = bitmapBitmapFactory.decodeResource(context.getResources(), R.drawable.my_graphical_element, options);
// 'sBitmap' is a Bitmap reference, while 'options' is BitmapFactory.Options
最后是我设置的地方:
setContentView(R.layout.main);
...
ImageView imageViewMyGraphicalImageElement= (ImageView) findViewById(R.id.imageViewMyGraphicalImageElement);
imageViewMyGraphicalImageElement.setImageBitmap(sBitmap);
问题: 显然,基于 xml 的解决方案在 调用 setContentView(...) 之前知道图像。预加载版本在该调用之后 设置图像。有什么不同吗?是否可以因此跳过系统完成的某些自动缩放或其他操作?
最佳答案
我刚刚为此写了一篇文章。希望能够回答你的问题。
https://plus.google.com/112740367348600290235/posts/VNAfFLDcKrw
ImageView
有 4 个 API 来指定图像。使用哪一个?有什么区别?
- setImageDrawable(可绘制可绘制对象)
- setImageBitmap(位图 bm)
- 设置图像资源(int resId)
- setImageURI(URI uri)
ImageView
,顾名思义,用于显示图像。但什么是图像? Bitmap
是图像,不难理解,为此我们使用 setImageBitmap
。然而,在内部,ImageView
有一个 Drawable
但没有 Bitmap
而这就是 setImageDrawable
的用途。当你调用setImageBitmap
时,在内部,首先将位图包装到BitmapDrawable
,这是一个Drawable
,然后调用setImageDrawable
。
这是代码。
public void setImageBitmap(Bitmap bm) {
setImageDrawable(new BitmapDrawable(mContext.getResources(), bm));
}
那么,API 3 和 4 呢?
您应该已经知道有很多方法可以从文件路径、Uri 或资源文件创建位图。
BitmapFactory.decodeFile(String pathName)
BitmapFactory.decodeStream(Inputstream)
BitmapFactory.decodeResource(Resource res, int id)
BitmapFactory.decodeByteArray(byte[] data)
意识到这一点,就很容易理解setImageResource
/setImageUri
和setImageBitmap
一样了。
综上所述,setImageDrawable
是其他API依赖的原始函数。其他 3 个只是辅助方法,可以让您编写更少的代码。
此外,记住 ImageView
实际上有一个 Drawable
很重要,它不一定是 BitmapDrawable
!您可以将任何 Drawable
设置为 ImageView 。
除了通过 Java API 设置 Drawable
之外,您还可以使用 XML 属性为 ImageView
设置源 Drawable
。请参见下面的示例。请注意,形状可以是图像文件(.png、.jpg、.bmp)或 xml 文件。
<ImageView
android:layout_width="match_parent"
android:layout_height="50dip"
android:src="@drawable/shape"/>
形状.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF" android:angle="270"/>
<padding android:left="7dp" android:top="7dp android:right="7dp" android:bottom="7dp" />
<corners android:radius="8dp" />
</shape>
关于java - XML 与 setImageDrawable/setImageBitmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10972202/