使得对象自己旋转可以引起一些注意,但是如果你想要让用户和你的OpenGL ES图像交互呢?关键在于重写你的GLSurfaceView的onTouchEvent()方法来监听触摸事件。
这节课告诉你怎样去监听触摸事件,让用户来旋转OpenGL ES对象。
为了使你的应用能响应出没时间,实现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-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。
public class MyGLRenderer implements GLSurfaceView.Renderer {
...
public volatile float mAngle;
public float getAngle() {
return mAngle;
}
public void setAngle(float angle) {
mAngle = angle;
}
}
为了应用触摸事件产生的旋转,修改之前的代码如下
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);
}
在你完成了上述步骤之后,运行程序并拖动手指来旋转三角形。