Bitmap width/height different after loading from Resource

X-Tender picture X-Tender · Feb 26, 2011 · Viewed 21.4k times · Source

1st. i'am new to Android coding :)

What I do is I load an Bitmap from my res/drawable-mdpi with

BitmapFactory.decodeResource(getResources(), R.drawable.cat_ground_01);

after I Log out the width/height of the Bitmap it tells me an other value then the Bitmap realy is.

That's kinda difficult to place Bitmaps pixelperfect e.g. overlap a bitmap of an face with an bitmap of mouth.

maybe I'am just missing some knowledge for this Topic :9 I hope you can help.

Answer

xandy picture xandy · Feb 26, 2011

When you do Bitmapfactory.decodeResource(), Android by default will choose the "matched" dpi version to decode, what happen in your mentioned code will yields:

  1. You can't specify whether it is in mdpi, hdpi or whatever, it will choose the version that match your running System. i.e., if you are running on a mdpi device, it will decode the mdpi version; in ldpi, then the ldpi version.

  2. Suppose you are using a hdpi device, but no mdpi resource is defined, what it will do is take your mdpi resource, and during decode, it will make it into hdpi (i.e., it enlarge your mdpi bitmap to about 1.5x larger); again, if your device has lower resolution then it will shrink the image

I guess this is what happens to you. For BitmapFactory, it actually has the option to NOT scaling the image:

http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html

Set the inScaled to false will do.