Reputation: 20355
I find that the unit of the coordinate system of Canvas is different from that of screen.
For example in my case as below:
For one particular point, its on-screen coordinate obtained from ImageView.getX()
and ImageView.getY()
is (336, 578)
.
Then by trial and error, I draw a dot on the Canvas so that this dot falls EXACTLY the same position as the ImageView. I called canvas.drawCircle(330, 440, radius, paint);
to achieve this.
Here comes the question:
Why would the 2 coordinates, (336, 578) and (330, 440), different?
Is it because the screen and the canvas use different units?
Is it an issue regarding pixel, dp and all that?
Upvotes: 6
Views: 3942
Reputation: 1593
You could try converting to and from window coordinates using View.getLocationInWindow
this way you'll always be sure you are using the same coordinates system.
Coordinates of ImageView.getX
an Y
are relative to the parent. Canvas coordinates are relative to the view. This could cause the differences
Edit:
I assume in one place you get the coordinates of the view (using getX
and getY
). Convert these to window coordinates. Call these viewXY[]
.
When you need to use them, to draw in your canvas, also convert the top and left coordinates to window coordinates. We call these canvasXY[]
.
Now, the X
position to draw at would be viewXY[0] - canvasXY[0]
, and the Y
position would be viewXY[1] - canvasXY[1]
.
Upvotes: 1
Reputation: 11437
A view's position co-ordinates are always relative to it's parent. It's like saying, where with respect to it's parent is this view placed.
There in another thing, screen Co-ordinate. This says where with respect to the window top/left (think actual physical screen) is this object placed. This can be obtained through View.getLocationOnScreen
.
If you want to compare two locations, they will only be equivalent if the parent view of both these locations is same or you're using absolute screen co-ordinates. Otherwise, you'll only get results that "seem" different.
If you want to unify the two either take them to a common parent or use absolute co-ordinates.
Upvotes: 1