Android---OpenGL ES之響應觸屏事件
像旋轉三角形那樣,讓對象根據預設的程序來移動,以便有助于獲取人們的關注,但是如 果想要讓你的OpenGL ES圖形跟用戶交互,應該怎樣做呢?要讓你的OpenGL ES應用程序能夠觸碰交互的關鍵是擴展你的GLSurfaceView實現,重寫它的onTouchEvent()方法來監聽觸碰事件。
本文介紹如何監聽觸碰事件,讓用戶可以旋轉OpenGL ES對象。
設置觸碰監聽器
為了讓你的OpenGL ES應用程序響應觸碰事件,你必須在你GLSurfaceView類中實現onTouchEvent()事件。以下實現的示例顯示如何監聽MotionEvent.ACTION_MOVE事件,并把它們轉換成圖形旋轉的角度。
- @Override
- public boolean onTouchEvent(MotionEvent e) {
- // MotionEvent reportsinput details from the touch screen
- // and other inputcontrols. In this case, you are only
- // interested in eventswhere the touch position changed.
- float x = e.getX();
- float y = e.getY();
- switch (e.getAction()) {
- case MotionEvent.ACTION_MOVE:
- float dx = x - mPreviousX;
- float dy = y - mPreviousY;
- // reverse direction of rotation above the mid-line
- if (y > getHeight() / 2) {
- dx = dx * -1 ;
- }
- // reverse direction of rotation to left of the mid-line
- if (x < getWidth() / 2) {
- dy = dy * -1 ;
- }
- mRenderer.mAngle += (dx + dy) * TOUCH_SCALE_FACTOR; // = 180.0f /320
- requestRender();
- }
- mPreviousX = x;
- mPreviousY = y;
- return true;
- }
注意,計算旋轉的角度之后,這個方法調用了requestRender()方法來告訴渲 染器,到了渲染幀的時候了。上例中所使用的方法是最有效的,只有在有旋轉變化時,幀才會被重繪。但是要想只在數據變化的時候,才請求渲染器重繪,就要使用 setRenderMode()方法來設置繪制模式。
- publicMyGLSurfaceView(Context context){
- ...
- // Render the view onlywhen there is a change in the drawing data
- setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
- }
暴露旋轉的角度
上例代碼要求你通過添加一個公共的成員變量,通過渲染器把旋轉的角度暴露出來。因為渲染器代碼運行在一個獨立于主用戶界面線程之外的線程中,所以你必須聲明一個公共變量,代碼如下:
- publicclassMyGLRendererimplementsGLSurfaceView.Renderer{
- ...
- public volatile float mAngle;
應用旋轉
以下代碼完成由觸碰輸入所產生的旋轉:
- publicvoidonDrawFrame(GL10 gl){
- ...
- // Create a rotation forthe triangle
- // long time =SystemClock.uptimeMillis() % 4000L;
- // float angle = 0.090f *((int) time);
- Matrix.setRotateM(mRotationMatrix, 0, mAngle, 0, 0, -1.0f);
- // Combine the rotationmatrix with the projection and camera view
- Matrix.multiplyMM(mMVPMatrix, 0, mRotationMatrix, 0, mMVPMatrix, 0);
- // Draw triangle
- mTriangle.draw(mMVPMatrix);
- }
本文譯自:http://developer.android.com/training/graphics/opengl/touch.html