如何获得android中所有分辨率的图像相同的坐标?

mal*_*ika 7 android coordinates imageview

我坚持为所有分辨率获取图像的x&y坐标.

  1. 320,对于具有屏幕配置的设备,例如:
    • 240x320 ldpi(QVGA手机)
    • 320x480 mdpi(手机)
    • 480x800 hdpi(高密度手机)
  2. 480,用于480x800 mdpi(平板电脑/手机)等屏幕.
  3. 600,适用于600x1024 mdpi(7"平板电脑)等屏幕.
  4. 720,用于720x1280 mdpi(10"平板电脑)等屏幕.

我创建了我的图像视图,原始大小为1500 x 1119的图像.当我触摸图像时,我可以通过onTouch()获得坐标.如果在所有设备中更改了坐标,我的问题.我在不同的欺骗中得到不同的x和y值.我无法为所有分辨率获得相同的x和y值.我该如何解决这个问题?

Dav*_*sey 3

这是一个比您的特定布局要求稍微更通用的解决方案。这假设您知道源图像的尺寸并想知道其上被点击的坐标,忽略屏幕尺寸和分辨率。尽管您的布局定义了与源图像匹配的宽度和高度,但这将处理宽度和高度设置为 或 的布局wrap_contentmatch_parent前提是您使用的比例类型之一适合视图边界内的整个图像并保留纵横比(例如fitXY)。

我没有ScrollView像你一样尝试过这个 inside s,但理论上它应该没问题。

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);
Run Code Online (Sandbox Code Playgroud)