Search code examples
androidbitmapscaleresolution

How to scale bitmaps on View.Canvas in Android?


I have a View-derived class where I draw a 790x500 (yes, this is odd but it has to stay this way) bitmap directly on the canvas in onDraw. This looks ok on my Nexus S, but when I run my app on a device with a smaller screen (e.g. Wildfire) I only see the upper left part of the bitmap. What am I missing here?

This is a game-like app where I draw a number of bitmaps on certain coordinates. I really don't want to have different pixel setups for LDPI, MDPI and HDPI (I have a good reason for this).

Q: How can I properly scale my bitmaps for any screen resolution? (Centering the game screen for large screens may be an option, but is not a must.) E.g. when I draw a 800x600 image on a 320x240 screen, the image is automatically stretched and when I output a pixel at 100x100, it becomes 40x40.


Solution

  • There are many forms of the drawbitmap() method. Choose the one that allows you to specify the source and destination rectangle. The source rectangle will be the size of your bitmap and the destination rectangle will be scaled to fit on the device display. Android will scale your bitmap when it draws it.

    Rect rs = new Rect();
    Rect rd = new Rect();
    rs.left = rs.top = 0;
    rs.right = 789;
    rs.bottom = 499;
    
    <calculate destination rectangle from device size>
    
    canvas.drawBitmap(myBitmap, rs, rd, null);
    

    You can also scale and translate (shift) the entire canvas

    canvas.scale(float scaleX, float scaleY);
    canvas.translate(float dx, float dy);