Pages

10 Jul 2014

ImageView.setImageBitmap and other ImageView's set image methods

Have you ever stumbled in a case that you use ImageView.setImageResource(R.drawable.your_image) and your image is displayed totally fine in all devices, then you want to make your ImageView more dynamic by put your image into a server, then use something (like Volley, UniversalImageLoader...) to load the image as a Bitmap, then use ImageView.setImageBitmap(your_bitmap) to display your image but it's displayed fine in all devices anymore?!

I got myself into that case today, after using ImageView.setImageBitmap(), my image is displayed too big in some devices and too small in some others. It took me an hour debugging and reading the ImaveView's source code and still couldn't figure out why but reminded me about Android's DisplayMetrics.
As we are developing Android and iOS versions parallel, both share the same resources, and I put all Android's image resources into drawable-xhdpi (as you may know, Android's xhdpi and iOS's retina have the same density), so when I use ImageView.setImageResource(), it displays my images pretty well on all current popular devices (exclude tablets), but why not ImageView.setImageBitmap()?!

The reason is ImageView.setImageResource() cares about device's density, but setImageBitmap() doens't seem to, I think it probably uses some default settings. So to fix it, just use Bitmap.setDensity() with an appropriate density from DensityMetrics. For example, in my case, I would use:

 bitmap.setDensity(DisplayMetrics.DENSITY_XHIGH);


That's it ;-)
Happy coding, guys!

No comments:

Post a Comment

Note: only a member of this blog may post a comment.