ImageView 四個(gè)指定圖片的方法區(qū)別

今天在看人家一個(gè)繼承ImagView的自定義控件,發(fā)現(xiàn)他覆寫了這下面這四個(gè)方法。就在網(wǎng)上找了下這四個(gè)方法有啥區(qū)別,最后在Google Plus上找到了下面的解釋。英文很差的我都看懂了,所以就不翻譯了,直接搬運(yùn)過(guò)來(lái)了。

ImageView has 4 APIs to specify the image. Which one to use? What is the difference?

  1. setImageDrawable(Drawable drawable)
  2. setImageBitmap(Bitmap bm)
  3. setImageResource(int resId)
  4. setImageURI(URI uri)

ImageView, by the name, is used to display an image. But what is a image? A Bitmap is-a image, not hard to understand and we use setImageBitmap for that purpose. However, internally, the ImageView has-a Drawable but not a Bitmap and that is what setImageDrawable for. When you call setImageBitmap, internally, first the bitmap will be wrapped to BitmapDrawable, which IS-A Drawable , and then call setImageDrawable.

Here is the code.

public void setImageBitmap(Bitmap bm) {
setImageDrawable(new BitmapDrawable(mContext.getResources(), bm));
}

So, what about the 3 and 4 API?

You should already know that that are bunches of ways to create a bitmap, from a file path, from the Uri, or from the resource file.

BitmapFactory.decodeFile(String pathName)
BitmapFactory.decodeStream(Inputstream)
BitmapFactory.decodeResource(Resource res, int id)
BitmapFactory.decodeByteArray(byte[] data)

Aware of this, it is easy to understand setImageResource/setImageUri is just same as setImageBitmap.

To sum up, setImageDrawable is the primitive function other APIs rely on. The other 3 are just helper methods making you write less code.

In addition, it is very important to keep in mind that ImageView actually has-a Drawable, which not necessarily to be a BitmapDrawable! You could set any Drawable to the Image view.

Besides setting the Drawable through Java API, you could also using XML attribution to set the source Drawable for ImageView. See example below. Note that the shape could be either an image file (.png,.jpg,.bmp) or xml file.

<ImageView
                           android:layout_width="match_parent"
                           android:layout_height="50dip"
                           android:src="@drawable/shape"/>

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>

原文鏈接(要梯子):
https://plus.google.com/+PierrChen/posts/VNAfFLDcKrw

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容