要响应触摸事件,就需要实现GLSurfaceView的onTouchEvent()方法来监听触摸事件。
下面的代码监听MotionEvent.ACTION_MOVE事件,然后旋转形状一个角度。
上面的实例代码需要公开旋转角度,当渲染代码运行在一个特别的线程中时,你需要声明一个公共变量为volatile的,作用是为了同步旋转的角度:
注释掉生成角度的代码,添加mAngle,它包含触摸时生成的角度:
设置一个触摸监听
下面的代码监听MotionEvent.ACTION_MOVE事件,然后旋转形状一个角度。
@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-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()方法:
public MyGLSurfaceView(Context context) { ... // Render the view only when there is a change in the drawing data setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); }
公开旋转角度
上面的实例代码需要公开旋转角度,当渲染代码运行在一个特别的线程中时,你需要声明一个公共变量为volatile的,作用是为了同步旋转的角度:
public class MyGLRenderer implements GLSurfaceView.Renderer { ... public volatile float mAngle;
应用旋转
注释掉生成角度的代码,添加mAngle,它包含触摸时生成的角度:
public void onDrawFrame(GL10 gl) { ... // 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 Matrix.multiplyMM(mMVPMatrix, 0, mRotationMatrix, 0, mMVPMatrix, 0); // Draw triangle mTriangle.draw(mMVPMatrix); }
运行效果如下:
![](https://img-my.csdn.net/uploads/201209/17/1347883651_8609.png)