Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitmap width/height different after loading from Resource

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.

like image 702
X-Tender Avatar asked Feb 26 '11 16:02

X-Tender


3 Answers

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.

like image 74
xandy Avatar answered Nov 17 '22 09:11

xandy


Can't you just put the resource in the nodpi folder?

i.e. res/drawable-nodpi

This is what I've done in the past.

like image 33
Kyle Avatar answered Nov 17 '22 09:11

Kyle


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

Check your options.inTargetDensity and options.inDensity after loading the Bitmap from /drawable. They are not equal (160 and 240 for example). If options.inScaled set to true (default) - that's why the Bitmap is being automatically rescaled.

Another way is to use Bitmap.createScaledBitmap in order to rescale an image after loading. Because sometimes you need inScaled=true

        //Target dimensions
        int iW = 300;
        int iH = 200;
        Bitmap mOriginalBitmap = new Bitmap;
        BitmapFactory.Options options = new BitmapFactory.Options();
        //Load image from resource
        mOriginalBitmap = BitmapFactory.decodeResource(getResources(), 
                R.drawable.sample_image_900px, options);
        //Scale to target size
        mOriginalBitmap = Bitmap.createScaledBitmap(mOriginalBitmap, iW, iH, true); 
like image 4
pbu Avatar answered Nov 17 '22 10:11

pbu