跨设备在自定义图像视图上获取位置

Get position on a custom imageview across devices

我有一个应用程序使用图像上的坐标来固定标记。

final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                if (imageView.isReady()) {
                    sCoord = imageView.viewToSourceCoord(e.getX(), e.getY());

                    imageView.setPin(new PointF(sCoord.x,sCoord.y));
                    Toast.makeText(getApplicationContext(), "Single tap: " + ((int) convertPixelsToDp(sCoord.x)) + ", " + ((int) convertPixelsToDp(sCoord.y)), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Something is not right!", Toast.LENGTH_SHORT).show();
                }
                return true;
            }
        });

现在正在对点和点进行一些计算并更改标记的位置。它在正在使用的设备上工作正常,但当我使用另一台设备时,它显示随机位置(这很明显)。

我尝试this将坐标(像素)更改为 dp 单位,然后将图像固定到该位置,但仍然无效。

/**
 * This method converts dp unit to equivalent pixels, depending on device density. 
 * 
 * @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels
 * @param context Context to get resources and device specific display metrics
 * @return A float value to represent px equivalent to dp depending on device density
 */
public static float convertDpToPixel(float dp, Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float px = dp * (metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
    return px;
}

/**
 * This method converts device specific pixels to density independent pixels.
 * 
 * @param px A value in px (pixels) unit. Which we need to convert into db
 * @param context Context to get resources and device specific display metrics
 * @return A float value to represent dp equivalent to px value
 */
public static float convertPixelsToDp(float px, Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float dp = px / (metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
    return dp;
}

假设我有一家商店的平面图,我想要在门附近做一个标记。所以我获取坐标并使用上述函数将其转换为 dp,然后将该 dp 位置传递给另一个设备,然后将该 dp 转换为像素并使用该位置固定标记,但它不起作用。显示随机位置。

//trying
float x=convertDpToPixel(sCoord.x);
float y=convertDpToPixel(sCoord.y);
imageView.setPin(new PointF(x,y));

欢迎任何建议。谢谢

解决这个问题的方法就是使用百分比方法,为了详细说明给定的答案,我将展示一些简单的数学。

此计算过程需要以下值:

  • imageWidth = 图片从左到右的宽度。
  • imageHeight = 图片从上到下的高度。
  • xOccupation = x坐标从左到右的占用。
  • yOccupation = y坐标从上到下占用的高度。

要计算 xPercentage 和 yPercentage,我们将使用以下公式:

  • x百分比 = xOccupation/imageWidth
  • y百分比 = yOccupation/imageHeight

获得这 2 个值后,您现在可以将其发送到您的服务器并在各种设备中访问相同的值,无论大小密度如何。

客户端设备需要通过反向公式重新计算 x 和 y 坐标。

  • new-x-坐标 = newImageWidth*xPercentage.
  • 新的 y 坐标 = newImageHeight*yPercentage.