Android Training - 使用OpenGL ES(6) - 响应触摸事件

要响应触摸事件,就需要实现GLSurfaceView的onTouchEvent()方法来监听触摸事件。

设置一个触摸监听

下面的代码监听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);
}
运行效果如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值