2011-07-28 137 views
9

我使用GestureListener在Android SurfaceView中捕獲了MotionEvent長時間點擊。然後,我需要將MotionEvent的座標轉換爲畫布座標,從中可以生成自定義地圖座標(而不是Google地圖)。如何正確地將像素座標轉換爲Android中的畫布座標?

從我看過的內容來看,我給出了MotionEvent e,e.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對象?

+0

你有沒有試過'翻譯(DX浮動,浮動DY)'? –

+0

我看着它。不幸的是,我並沒有畫在畫布上。我需要實際的座標。一旦我獲得畫布座標,我計劃將畫布座標轉換爲將用於導航的應用程序的地圖座標。 – Phil

+0

真的沒有人?這是否與屏幕尺寸/分辨率/深度以及畫布的Rect對象有關?以前沒有人做過這種翻譯嗎? – Phil

回答

0

如果我理解正確,你有一個畫布視圖裏面surfaceview。如果是的話 試試VIEW.getLeft() | getTop()返回left |視圖相對於其父項的頂部位置。

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

感謝您的想法。我試了一下,它仍然無法正常工作。 – Phil

5

那麼,你必須在X,Y顯示在屏幕像素,並且你可以通過調用畫布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。我認爲它需要在活動內部進行初始化才能工作。

+0

感謝您的想法。我試過了,但它仍然無法正常工作。 – Phil

+0

錯誤是什麼? – Noah

+0

沒有錯誤。它提供了一些翻譯,但它不是正確的翻譯。無論我按什麼位置,它都會在屏幕頂部找到畫布座標方式。 – Phil

8

您可以嘗試使用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]; 
1

最近,我在這個問題而做的事情非常相似經過一番摸索與大量的谷歌搜索我結束了適應這個答案(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. 

有跡象表明,這裏可以應用一些明顯的優化,但我認爲它是更清晰這個樣子。

0

如果您使用的滾動,然後在畫布上的實際y是

float y = event.getY() + arg0.getScrollY(); 
相關問題