標籤:
原文地址:http://android.xsoftlab.net/training/graphics/opengl/touch.html
使圖形按照程式設計的軌跡旋轉對OpenGL來說還是不能發揮出它應有的實力。但要是能使使用者可以直接控製圖形的旋轉,這才是OpenGL的真正目的。它真正的關鍵所在就是使程式可以互動式觸摸。這主要靠重寫GLSurfaceView的onTouchEvent()的方法來實現觸摸事件的監聽。
這節課將會展示如何監聽觸摸事件來使使用者可以旋轉圖形。
設定觸摸監聽器
為了可以使OpenGL監聽觸摸事件,必須重寫GLSurfaceView類中的onTouchEvent()方法。下面的實現展示了如何監聽MotionEvent.ACTION_MOVE事件,以及如何使事件驅動圖形的旋轉.
private final float TOUCH_SCALE_FACTOR = 180.0f / 320;private float mPreviousX;private float mPreviousY;@Overridepublic boolean onTouchEvent(MotionEvent e) { // MotionEvent reports input details from the touch screen // and other input controls. In this case, you are only // interested in events where 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.setAngle( mRenderer.getAngle() + ((dx + dy) * TOUCH_SCALE_FACTOR)); requestRender(); } mPreviousX = x; mPreviousY = y; return true;}
這裡需要注意的是,在計算完旋轉的角度之後,這個方法調用了requestRender()方法,這個方法會通知渲染器可以渲染了。這個方法放在這個地方是最合適的,因為幀在這之前並不需要重新繪製,除非在角度上發生了變化。不管怎麼樣,這個方法並不會對效率有任何影響,除非你也設定了在資料發生改變的時候重新繪製的請求。這種請求通過setRenderMode()方法設定,所以要確保下面這行代碼沒有被注釋:
public MyGLSurfaceView(Context context) { ... // Render the view only when there is a change in the drawing data setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);}
暴露旋轉角度
上面的範例程式碼會要求提供一個公開的成員方法來暴露旋轉的角度。一旦渲染代碼運行在子線程當中,那麼必須將這個公用成員聲明為volatile。下面的代碼聲明了這個volatile的屬性,並暴露了它的get,set方法:
public class MyGLRenderer implements GLSurfaceView.Renderer { ... public volatile float mAngle; public float getAngle() { return mAngle; } public void setAngle(float angle) { mAngle = angle; }}
請求旋轉
為了觸摸事件驅動旋轉,需要注釋產生角度的代碼,然後添加mAngle成員屬性,mAngle中包含了觸摸事件所產生的角度:
public void onDrawFrame(GL10 gl) { ... float[] scratch = new float[16]; // Create a rotation for the triangle // long time = SystemClock.uptimeMillis() % 4000L; // float angle = 0.090f * ((int) time); Matrix.setRotateM(mRotationMatrix, 0, mAngle, 0, 0, -1.0f); // Combine the rotation matrix with the projection and camera view // Note that the mMVPMatrix factor *must be first* in order // for the matrix multiplication product to be correct. Matrix.multiplyMM(scratch, 0, mMVPMatrix, 0, mRotationMatrix, 0); // Draw triangle mTriangle.draw(scratch);}
如果完成了上面所描述的步驟,那麼啟動程式,然後在螢幕上拖動就可以使三角形旋轉起來:
Android官方開發文檔Training系列課程中文版:OpenGL繪圖之響應觸摸事件