Android - Drawing on the different devices

2019-05-19 06:35发布

问题:

In my app I create a canvas and add some bitmaps on it. The problem is that the objects are adding why touch the screen. So on one screens they appear on the middle on different the same, but their position in pixels are different.

I mean that I got tablet and smartphone. When I touch one the object appear on both devices (multiplayer) but its not in the same place, because its passing the position by x and y.

If someone understand what I mean, can you help me? Probably it must have something common with counting the ratio.

回答1:

I am guessing the problem you are having is that the screens are different resolutions and you are passing pixel data. You will need to use dp values and before sending them convert the dp to pixel values. On the receiving device you will need to convert the pixel values being sent back to dp on the given device. Use the methods below for the conversion.

To Convert DP to Pixels:

    final float scale = getResources().getDisplayMetrics().density;
    int pixelValue = (int) (DESIRED_DP_VALUE * scale + 0.5f);

To Convert Pixels to DP:

    final float scale = getResources().getDisplayMetrics().density;
    int dpValue = (int) ((DESIRED_PIXEL_VALUE) - 0.5f / scale);

The call to getDisplayMetrics().density is what will give you a scale value based on the current device. The dp value is meant to be density independent.



回答2:

How do you define the metrics? If you are using pixels, use a density independent solution:

public int GetDipsFromPixel(float pixels)
{
   // Get the screen's density scale
   final float scale = getResources().getDisplayMetrics().density;
   // Convert the dps to pixels, based on density scale
   return (int) (pixels * scale + 0.5f);
} 

And use it like this in you class:

 textView.setHeight(GetDipsFromPixel(50));

This way the the height of the textview will be the same dps on both devices, even if their resolution is different.