Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get same co-ordinates for image for all resolutions in android?

I stucked with getting x & y co-ordinates of an image for all resolutions.

  1. 320, for devices with screen configurations such as:
    • 240x320 ldpi (QVGA handset)
    • 320x480 mdpi (handset)
    • 480x800 hdpi (high density handset)
  2. 480, for screens such as 480x800 mdpi (tablet/handset).
  3. 600, for screens such as 600x1024 mdpi (7" tablet).
  4. 720, for screens such as 720x1280 mdpi (10" tablet).

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?

like image 963
malavika Avatar asked Jun 09 '14 10:06

malavika


1 Answers

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 ScrollViews 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);
like image 88
Dave Morrissey Avatar answered Nov 14 '22 18:11

Dave Morrissey