Android---OpenGL ES之响应触屏事件

来源:互联网 发布:win7怎么查看网络凭据 编辑:程序博客网 时间:2024/04/29 14:24

本文译自:http://developer.android.com/training/graphics/opengl/touch.html

像旋转三角形那样,让对象根据预设的程序来移动,以便有助于获取人们的关注,但是如果想要让你的OpenGL ES图形跟用户交互,应该怎样做呢?要让你的OpenGL ES应用程序能够触碰交互的关键是扩展你的GLSurfaceView实现,重写它的onTouchEvent()方法来监听触碰事件。

本文介绍如何监听触碰事件,让用户可以旋转OpenGL ES对象。

设置触碰监听器

为了让你的OpenGL ES应用程序响应触碰事件,你必须在你GLSurfaceView类中实现onTouchEvent()事件。以下实现的示例显示如何监听MotionEvent.ACTION_MOVE事件,并把它们转换成图形旋转的角度。

@Override
public
boolean onTouchEvent(MotionEvent e) {
    // MotionEvent reportsinput details from the touch screen
    // and other inputcontrols. In this case, you are only
    // interested in eventswhere 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()方法来设置绘制模式。

publicMyGLSurfaceView(Context context){
   
...
    // Render the view onlywhen there is a change in the drawing data
    setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);

}

暴露旋转的角度

上例代码要求你通过添加一个公共的成员变量,通过渲染器把旋转的角度暴露出来。因为渲染器代码运行在一个独立于主用户界面线程之外的线程中,所以你必须声明一个公共变量,代码如下:

publicclassMyGLRendererimplementsGLSurfaceView.Renderer{
   
...
    public volatile float mAngle;

应用旋转

以下代码完成由触碰输入所产生的旋转:

publicvoidonDrawFrame(GL10 gl){
   
...
    // Create a rotation forthe triangle
    // long time =SystemClock.uptimeMillis() % 4000L;
    // float angle = 0.090f *((int) time);
    Matrix.setRotateM(mRotationMatrix, 0, mAngle, 0, 0, -1.0f);

    // Combine the rotationmatrix with the projection and camera view
    Matrix.multiplyMM(mMVPMatrix, 0, mRotationMatrix, 0, mMVPMatrix, 0);

    // Draw triangle
    mTriangle.draw(mMVPMatrix);
}

以下是示例程序的运行效果

图1.使用触碰输入来旋转三角形