Search code examples
androidandroid-canvasandroid-viewandroid-screen

Draw the same circle on the same image on two different devices (different screen density)


I have an image on two different devices with different screen size and density.

Using a canvas, I want to draw a circle on device A image, then send the center coordinates to device B, and draw the circle in the same position, even if the same image has a different size.

What I do on device A before sending the the x coordinate is the following:

float density = getResources().getDisplayMetrics().density;
int width = getWidth();
float inchesLength = width/density;
float scaledXCenter = xCenter / inchesLength;

I do the same for the y coordinate.

On device B, I get the same parameters and multiply the received coordinate for the inchesLenght:

float density = getResources().getDisplayMetrics().density;
int width = getWidth();
float inchesLength = width/density;
float restoredXCenter = scaledXCenter * inchesLength;

I am testing this on AVDs. The problem is that each AVD has a screen density of 1, even if I can clearly see that on the smaller device (device A), the same image is fully displayed, but occupies a smaller space!

Should this approach work when working on real devices?

Is there any better way to do it?


Solution

  • find the width and height of the canvas and by dividing width and height find a ratio. This ratio should be multiplied with each value

    Here is the sample code

    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.view.View;
    
    public class GameCanvas extends View {
        private Paint paint = new Paint();
        private float canvasWidth;
        private float canvasHeight;
        private float ratio;
    
        public GameCanvas(Context context) {
            super(context);
            // TODO Auto-generated constructor stub
        }
    
        public void onDraw(Canvas canvas) {
            canvasWidth = canvas.getWidth();
            canvasHeight = canvas.getHeight();
            ratio=canvasWidth/canvasHeight;
    
            paint.setColor(Color.BLACK);
            paint.setStrokeWidth(3);
            //canvas.drawRect(30*ratio, 30*ratio, 100*ratio, 200*ratio, paint);
            paint.setStrokeWidth(0);
            paint.setColor(Color.CYAN);
            canvas.drawRect(33*ratio, 60*ratio, 77*ratio, 77*ratio, paint);
            paint.setColor(Color.YELLOW);
            canvas.drawRect(33*ratio, 33*ratio, 77*ratio, 60*ratio, paint);
    
        }
    }