Four ways to set Images

Source: Internet
Author: User

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. 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 APIs?

You shoshould already know 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 coshould set any Drawable to the Image view.

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

 



Shape. xml

     
      
      
  
 ?


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.