I stucked with getting x & y co-ordinates of an image for all resolutions.
I have created my image view with original size of an image like 1500 x 1119. When i touched the image i can get the co-ordinates using by onTouch(). My issue if the co-ordinates are changed in all device. I am getting different x & y values in different deceives . I can't get same x & y values for all the resolutions. How can i resolve this?
Here's a slightly more generic solution than your particular layout requires. This assumes you know the dimensions of the source image and want to know the coordinates on it that were tapped, ignoring screen size and resolution. Although your layout has defined width and height that appears to match the source image, this will handle layouts with width and height set to either wrap_content
or match_parent
, provided you're using one of the scale types that fits the whole image inside the view bounds and preserves the aspect ratio (e.g. fitXY
).
I haven't tried this inside ScrollView
s as you have yours but in theory it should be fine.
int sourceWidth = 1500;
int sourceHeight = 1119;
// Find view dimensions
int width = view.getWidth();
int height = view.getHeight();
// Assuming image has been scaled to the smaller dimension to fit, calculate the scale
float wScale = (float)width/(float)sourceWidth;
float hScale = (float)height/(float)sourceHeight;
float scale = Math.min(wScale, hScale);
// Find the offset in the direction the image doesn't fill the screen
// For ImageViews that wrap the content, both offsets will be 0 so this is redundant
int offsetX = 0;
int offsetY = 0;
if (wScale <= hScale) {
offsetY = (int)((height/2) - ((scale * sourceHeight)/2));
} else {
offsetX = (int)((width/2) - ((scale * sourceWidth)/2));
}
// Convert event coordinates to image coordinates
int sourceX = (int)((event.getX() - offsetX) / scale);
int sourceY = (int)((event.getY() - offsetY) / scale);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With