What is the unit of the canvas coordinate system? - Android

I find that the Canvas coordinate system unit is different from the screen unit.

For example, in my case, as shown below:

For one specific point, its screen coordinate obtained from ImageView.getX() and ImageView.getY() is (336, 578) .

Then, by trial and error, I draw a point on the canvas, so that this point falls EXACTLY to the same position as ImageView. I called canvas.drawCircle(330, 440, radius, paint); to achieve this.

The question arises:

Why are the two coordinates (336, 578) and (330, 440) different?

Is it because different units are used on the screen and on canvas?

Is this a problem with pixel, dp and all that?

+6
source share
2 answers

You can try to convert to and from window coordinates using View.getLocationInWindow so you will always be sure that you are using the same coordinate system.

ImageView.getX an Y coordinates refer to the parent. The coordinates of the canvas relative to the view. This may lead to differences.

Edit: I assume that in one place you get the coordinates of the view (using getX and getY ). Convert them to window coordinates. Name these viewXY[] .

When you need to use them to draw your canvas, also convert the top and left coordinates to the coordinates of the window. We call these canvasXY[] .

Now the X position for drawing will be viewXY[0] - canvasXY[0] , and the Y position will be viewXY[1] - canvasXY[1] .

+1
source

The coordinates of the view position are always related to it by the parent. This is how to say where in relation to this the parent object is located.

Elsewhere, the coordinate of the screen. This indicates where this object is located in relation to the top / left window (I think the actual physical screen). This can be obtained using View.getLocationOnScreen .

If you want to compare two locations, they will be equivalent only if the parent view of both of these locations is the same or you use absolute screen coordinates. Otherwise, you will get only those results that "seem" different.

If you want to combine the two or take them into a common parent or use absolute coordinates.

+1
source

Source: https://habr.com/ru/post/949283/


All Articles