2013-02-11 139 views
-1

我是Android OpenGL的新手,我正在嘗試使用OpenGL繪製按鈕我已經爲GLSurface添加了手勢監聽器現在我有motionevent,當用戶觸摸時。我的問題是如何將motionevent.getx和motionevent.gety(它們在像素範圍 中)轉換爲視圖的窗口或對象座標?Android OpenGLES 2.0按鈕

回答

0

我發現這個問題發佈的解決方案,如果有人需要它的情況下。

public float[] convertToObjectCoordinates(MotionEvent event) { 
     float[] worldPos = new float[2]; 
     float[] invertedMatrix, transformMatrix, 
       normalizedInPoint, outPoint, mProjMatrix, mVMatrix; 
     invertedMatrix = new float[16]; 
     transformMatrix = new float[16]; 
     mProjMatrix = new float[16]; 
     mProjMatrix = mRenderer.getmProjMatrix(); 
     mVMatrix = new float[16]; 
     //Change the Proj and ModelView matrix according to your model and view matrix or you can use your mvpMatrix directly instead of transform Matrix          
     Matrix.setLookAtM(mVMatrix, 0, 0, 0, -3, 0, 0, 0f, 0.0f, 1.0f, 0.0f); 
     normalizedInPoint = new float[4]; 
     outPoint = new float[4]; 
     float y = screenHeight - event.getY(); 
     setHeightAndWidth(); 
     normalizedInPoint[0] = (float) ((event.getX()) * 2.0f/screenWidth - 1.0); 
     normalizedInPoint[1] = (float) ((y) * 2.0f/screenHeight - 1.0); 
     normalizedInPoint[2] = - 1.0f; 
     normalizedInPoint[3] = 1.0f; 
     Matrix.multiplyMM(transformMatrix, 0, mProjMatrix, 0, mVMatrix, 0); 
     Matrix.invertM(invertedMatrix, 0, transformMatrix, 0); 
     Matrix.multiplyMV(outPoint, 0, invertedMatrix, 0, normalizedInPoint, 0); 
     if (outPoint[3] != 0.0) 
     { 
      worldPos[0] = outPoint[0]/outPoint[3]; 
      worldPos[1] = outPoint[1]/outPoint[3]; 
     } else { 
      Log.e("Error", "Normalised Zero Error"); 
     } 
     return worldPos; 
    } 

這是從下面的帖子爲Android的OpenGL2.0翻拍: Android OpenGL ES 2.0 screen coordinates to world coordinates 埃羅爾的回答 感謝埃羅爾對他的回答。

 public void setHeightAndWidth() { 
     screenHeight = this.getHeight(); 
     screenWidth = this.getWidth(); 
     } 

上面的方法應該寫在GLSurfaceView類中,以便它給出確切的視圖的高度和寬度。如果您的視圖佔用完整的屏幕,您也可以使用顯示指標獲取完整的屏幕寬度和高度。