簡體   English   中英

如何在Android中正確地將像素坐標轉換為畫布坐標?

[英]How do I correctly translate pixel coordinates to canvas coordinates in Android?

我捕捉MotionEvent用於在Android長時間點擊SurfaceView使用GestureListener 然后我需要將MotionEvent的坐標轉換為畫布坐標,從中我可以生成自定義地圖坐標(而不是Google地圖)。

根據我的閱讀,我認為給定e.getX() MotionEvent ee.getX()e.getY()得到像素坐標。 如何將這些坐標轉換為SurfaceView的畫布坐標?

這是我的GestureListener用於收聽長時間點擊:

/**
* Overrides touch gestures not handled by the default touch listener
*/
private class GestureListener extends GestureDetector.SimpleOnGestureListener {

  @Override
  public void onLongPress(MotionEvent e) {
     Point p = new Point();
     p.x =  (int) e.getX();
     p.y = (int) e.getY();
     //TODO translate p to canvas coordinates
  }
}

提前致謝!

編輯:這是否與屏幕尺寸/分辨率/深度和畫布'Rect對象有關?

您可以嘗試使用MotionEvent.getRawX()/getRawY()方法而不是getX()/getY()

// get the surfaceView's location on screen
int[] loc = new int[2];
surfaceView.getLocationOnScreen(loc);
// calculate delta
int left = e.getRawX()-loc[0];
int top = e.getRawY()-loc[1];

好吧,你有x,y顯示的屏幕px,你可以通過以下方式調用canvas px:

Canvas c = new Canvas();
int cx = c.getWidth();
int cy = c.getHeight();
...
Display display = getWindowManager().getDefaultDisplay(); 
int sx = display.getWidth();
int sy = display.getHeight();

然后,您可以進行數學計算以在視圖和屏幕中使用給定的px映射屏幕觸摸視圖。

canvasCoordX = p.x*((float)cx/(float)sx);
canvasCoordY = p.y*((float)cy/(float)sy);

有關屏幕管理器的更多信息,請參閱http://developer.android.com/reference/android/view/WindowManager.html 我認為它需要在一個活動中初始化才能工作。

我最近在做一些非常類似的事情時遇到了這個問題,經過一些試驗和錯誤以及大量的谷歌搜索后我最終調整了這個答案( https://stackoverflow.com/a/9945896/1131180 ):

(e是一個MotionEvent,因此使用此代碼的最佳位置是onTouch或onLongPress)

mClickCoords = new float[2];

//e is the motionevent that contains the screen touch we
//want to translate into a canvas coordinate
mClickCoords[0] = e.getX();
mClickCoords[1] = e.getY();

Matrix matrix = new Matrix();
matrix.set(getMatrix());

//this is where you apply any translations/scaling/rotation etc.
//Typically you want to apply the same adjustments that you apply
//in your onDraw().

matrix.preTranslate(mVirtualX, mVirtualY);
matrix.preScale(mScaleFactor, mScaleFactor, mPivotX, mPivotY);

// invert the matrix, creating the mapping from screen 
//coordinates to canvas coordinates
matrix.invert(matrix); 

//apply the mapping
matrix.mapPoints(mClickCoords);

//mClickCoords[0] is the canvas x coordinate and
//mClickCoords[1] is the y coordinate.

有一些明顯的優化可以在這里應用,但我認為這種方式更清晰。

如果我理解正確你有一個畫面查看里面的surfaceview。 如果是這樣,請嘗試VIEW.getLeft() | getTop() 返回左邊的VIEW.getLeft() | getTop() | 視圖相對於其父級的頂部位置。

float x= e.getX() - canvasView.getLeft();
float y= e.getY() - canvasView.getTop();

如果你使用滾動,那么畫布上的實際y是

float y = event.getY() + arg0.getScrollY();

我在這些情況下所做的只是:

  1. 將監聽器放在任何View / ViewGroup上,通過單擊獲得其坐標
  2. 讓它在本地存儲
  3. 誰想要訪問它們應該只通過幫助方法請求它們。

翻譯完成了......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM