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



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

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;
            }
        });

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

我尝试这样做将坐标(像素)更改为 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 = 图像从左到右的宽度。
  • 图像高度 = 如果图像从上到下的高度。
  • xOccupation = 从左到右占用 x 坐标。
  • yOccupation = y 坐标从上到下的占用高度。

为了计算 xPercent 和 yPercent,我们将使用以下公式:

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

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

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

  • 新 x 坐标 = newImageWidth*xPercentage
  • 新 y 坐标 = newImageHeight*yPercentage

最新更新