响应触摸事件

编写:jdneo - 原文:<http://developer.android.com/training/graphics/opengl/touch.html>

让对象根据预设的程序运动(如让一个三角形旋转),可以有效地引起用户的注意,但是如果希望让OpenGL ES的图形对象与用户交互呢?让我们的OpenGL ES应用可以支持触控交互的关键点在于,拓展GLSurfaceView的实现,重写onTouchEvent()方法来监听触摸事件。

这节课将会向你展示如何监听触控事件,让用户旋转一个OpenGL ES对象。

配置触摸监听器

为了让我们的OpenGL ES应用响应触控事件,我们必须实现GLSurfaceView类中的onTouchEvent()方法。下面的例子展示了如何监听MotionEvent.ACTION_MOVE事件,并将事件转换为形状旋转的角度:

1. private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
2. private float mPreviousX;
3. private float mPreviousY;

5. @Override
6. public boolean onTouchEvent(MotionEvent e) {
7. // MotionEvent reports input details from the touch screen
8. // and other input controls. In this case, you are only
9. // interested in events where the touch position changed.

11. float x = e.getX();
12. float y = e.getY();

14. switch (e.getAction()) {
15. case MotionEvent.ACTION_MOVE:

17. float dx = x - mPreviousX;
18. float dy = y - mPreviousY;

20. // reverse direction of rotation above the mid-line
21. if (y > getHeight() / 2) {
22. dx = dx * -1 ;
23. }

25. // reverse direction of rotation to left of the mid-line
26. if (x < getWidth() / 2) {
27. dy = dy * -1 ;
28. }

30. mRenderer.setAngle(
31. mRenderer.getAngle() +
32. ((dx + dy) * TOUCH_SCALE_FACTOR));
33. requestRender();
34. }

36. mPreviousX = x;
37. mPreviousY = y;
38. return true;
39. }

注意在计算旋转角度后,该方法会调用requestRender()来告诉渲染器现在可以进行渲染了。这种办法对于这个例子来说是最有效的,因为图形并不需要重新绘制,除非有一个旋转角度的变化。当然,为了能够真正实现执行效率的提高,记得使用setRenderMode()方法以保证渲染器仅在数据发生变化时才会重新绘制图形,所以请确保这一行代码没有被注释掉:

1. public MyGLSurfaceView(Context context) {
2. ...
3. // Render the view only when there is a change in the drawing data
4. setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
5. }

公开旋转角度

上述样例代码需要我们公开旋转的角度,具体来说,是在渲染器中添加一个public成员变量。由于渲染器代码运行在一个独立的线程中(非主UI线程),我们必须同时将该变量声明为volatile。注意下面声明该变量的代码,另外对应的get和set方法也被声明为了public成员函数:

1. public class MyGLRenderer implements GLSurfaceView.Renderer {
2. ...

4. public volatile float mAngle;

6. public float getAngle() {
7. return mAngle;
8. }

10. public void setAngle(float angle) {
11. mAngle = angle;
12. }
13. }

应用旋转

为了应用触控输入所生成的旋转,注释掉创建旋转角度的代码,然后添加mAngle,该变量包含了触控输入所生成的角度:

1. public void onDrawFrame(GL10 gl) {
2. ...
3. float[] scratch = new float[16];

5. // Create a rotation for the triangle
6. // long time = SystemClock.uptimeMillis() % 4000L;
7. // float angle = 0.090f * ((int) time);
8. Matrix.setRotateM(mRotationMatrix, 0, mAngle, 0, 0, -1.0f);

10. // Combine the rotation matrix with the projection and camera view
11. // Note that the mMVPMatrix factor *must be first* in order
12. // for the matrix multiplication product to be correct.
13. Matrix.multiplyMM(scratch, 0, mMVPMatrix, 0, mRotationMatrix, 0);

15. // Draw triangle
16. mTriangle.draw(scratch);
17. }

当完成了上述步骤,我们就可以运行这个程序,并通过手指在屏幕上的滑动旋转三角形了:

ogl-triangle-touch