androidandroid-bitmap

BitmapFactory getWidth() getHeight() and pixels from actual picture size differ


I am a novice in Android Studio, and out of everything I am especially confused in tasks relating to BitmapFactory.

The problem I have is as followed. When I insert a jpg file with dimension(578x496) under drawable folder, and I do this

Bitmap mBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.background1));
Log.e("WIDTH", String.valueOf(mBitmap.getWidth());
Log.e("HEIGHT", String.valueOf(mBitmap.getHeight());

What I get is a dimension of (2312x1984), which exactly x4 bigger than the actual dimension. Is it because I have the file format as jpg and not png?

So what I decided to do was

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap mBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.background1,options));

and then set it as a background of my SurfaceView by,

public class GamePanel extends SurfaceView implements SurfaceHolder.Callback {
   public static final int WIDTH=578;
   public static final int HEIGHT=496;
   ....
   @Override
   public void draw(Canvas canvas){
    final int scaleXFactor = getWidth()/WIDTH;
    final int scaleYFactor = getHeight()/HEIGHT;

    if(canvas!=null){
        final int savedState = canvas.save();
        canvas.scale(scaleXFactor,scaleYFactor);
        bg.draw(canvas);
        canvas.restoreToCount(savedState);
    }

}

but this canvas.scale(scaleXFactor,scaleYFactor) only allow the background to fit horizontally but not vertically. So it is like

--------------------------------------    
|                IMG                  |
|                                     |
|-------------------------------------|   <-Viewed as "Landscape"
|         Black Empty Screen          |
|                                     |
|-------------------------------------|             

My understanding so far is that Bitmap is really important concept in any kinds of applications made from Android Studio, and when not implemented correctly, it causes application to crash through OOM error or simple slow down the application. Please shed me some light on this poor man, experts out there.


Solution

  • When you have an image in /res/drawable or /res/drawable-mdpi folder, and you call BitmapFactory.decodeResource() on a device with xxxhdpi density, BitmapFactory will scale up the bitmap for you, so that when you display it on the xxxhdpi screen, it will look proportionately the same as on a lower density screen.

    If you've decided that you really don't want this to happen, place the image in the /res/drawable-nodpi folder. Then it will decode at the same size on every platform. The image will look very different across different density devices when you display it, however.