Search code examples
androidbitmapandroid-2.3-gingerbread

Android bitmap getPixel depends on density?


Right to the code. Given

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId);
Drawable drawable = getResources().getDrawable(resId);

I get

bitmap.getWidth() == drawable.getIntrinsicWidth() == 9

though the actual image is 6x6 pixels. The point is that the density is 240, thus the scale is 1.5 to the DENSITY_DEFAULT = 160. That would not be such an issue itself, but bitmap.getPixel(x, y); does also work with the enlarged dimensions.

Settings bitmap's density seems to make no difference. How should I query the image for pixel at real position? I would rather not divide everything by the density (ofttimes not even possible).

Thanks


Solution

  • First a few comments on what's happening here. The Bitmap you get is actually resampled; its pixel data is for a 9x9 image. The method bitmap.getWidth() is not affected by calls to bitmap.setDensity().

    To load the Bitmap while preventing the Android framework from resampling it for you, create a BitmapFactory.Options instance and set inScaled to false, then pass this to decodeResource():

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inScaled = false;
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId, options);
    // Now bitmap.getWidth() == 6
    

    Note that it is the resampled version that is used in the UI (unless you explicitly work around that), so if you want to do bitmap.getPixel(x,y); on the Bitmap that is drawn in the UI, you should not make use of inScaled = false.