There is a picture (background) 480x800. I need to output a bitmap on top of the backgroader with certain coordinates. The problem is that on devices with a resolution of 480x800 is displayed correctly, and on others, respectively, with an offset. All pictures are in res / drawable directories. Later I plan to make all the pictures of different sizes and scatter them in their directories (hdpi, ldpi, etc.)

Screen sizes and other variables I get the following code (in the comments of their values):

Here I took the emulator 480x800:

DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics(); frameWidth = metrics.widthPixels; // 480 frameHeight = metrics.heightPixels; // 800 xDpi = metrics.xdpi; // 240 yDpi = metrics.ydpi; // 240 scaleFactor = getResources().getDisplayMetrics().density; // 1.5 

Here I took 720x1280:

 DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics(); frameWidth = metrics.widthPixels; // 720 frameHeight = metrics.heightPixels; // 1232 xDpi = metrics.xdpi; // 164.75676 yDpi = metrics.ydpi; // 165.03554 scaleFactor = getResources().getDisplayMetrics().density; // 1.0 

What is the principle to calculate the output coordinates so that the sprites / bitmaps are displayed the same way on all devices relative to the background / other objects / each other?

For clarity, added screenshots from two emulators: 480x800

720x1280

  • On your topic excellent article m.habrahabr.ru/post/136802 - Flippy
  • @ SergeyGrushin Please try to publish detailed answers containing a specific example of the minimum solution, supplementing them with a link to the source. Answers –references (as well as comments) do not add knowledge to the Runet. - Nicolas Chabanovsky ♦

1 answer 1

I answer my own question:

Suppose we need to display the sprite on the screen to the coordinate 140x200. We calculate everything relative to the base image, which is in the drawable-mdpi directory. I took the image 480x800 as a basis. Now we calculate the percentages of X and Y coordinates:

  procX=480/140; // =3.42857142857 procY=800/200; // =4 

When we know the percentage of the ratio of points and know the width and height of the screen (our frameWidth, frameHeight variables), we can calculate the coordinates on the screen with a different resolution:

  x=frameWidth/procX; y=frameHeight/procY; 

Check for the screen 720x1280:

  x=720/procX; // = 210 y=1280/procY // = 320 

Maybe this method is wrong, but quite working.