Search code examples
androidimagebitmapscalingresolutions

Android: How to support multiple screen resolutions when using SurfaceView


I've got a problem when supporting different Devices and their screens: I have game where I draw a lot of 70px*70px icons in a grid.

The .png File is 70*70 @ 315ppi.

In my java code I now draw the images to a grid with the following code:

for (int x = 0; x < Map.getxSize(); x++) {
        for (int y = 0; y < Map.getySize(); y++) {
            ballSprite.setX(x*70);
            ballSprite.setY(y*70);
            ballSprite.setCurrentFrame(Map.mArray[x][y]-1); //-1 because 0 field is empty
            ballSprite.onDraw(canvas);
        }
    }

the (x*70) works great with my Galaxy Nexus, but when I test it on a device with hdpi 800 the 70px value is way too high.

What is the best way to adapt this value to the different screens? Thanks for helping me out!


Solution

  • Multiply X and Y with proper scale factors.

    Display display = getWindowManager().getDefaultDisplay(); 
    int currentWidth = display.getWidth();  
    int currentHeight = display.getHeight();
    
    float scaleX = width that application was written for (in your case Galaxy Nexus width) / currentWidth  .
    float scaleY = height that application was written for (in your case Galaxy Nexus height) / currentHeight .
    

    ballSprite.setX(x*70*scaleX) etc...