Android官方开发文档Training系列课程中文版:OpenGL绘图之响应触摸事件
原文地址: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; @Override public 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-lineif (y > getHeight() / 2) {dx = dx * -1 ;}// reverse direction of rotation to left of the mid-lineif (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 datasetRenderMode(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 trianglemTriangle.draw(scratch); }如果完成了上面所描述的步驟,那么啟動程序,然后在屏幕上拖動就可以使三角形旋轉起來:
總結
以上是生活随笔為你收集整理的Android官方开发文档Training系列课程中文版:OpenGL绘图之响应触摸事件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用Kotlin开发Android应用初
- 下一篇: Android官方开发文档Trainin