【Android Developers Training】 67. 響應觸摸事件

注:本文翻譯自Google官方的Android Developers Training文檔,譯者技術通常,因爲喜好安卓而產生了翻譯的念頭,純屬我的興趣愛好。html

原文連接:http://developer.android.com/training/graphics/opengl/touch.htmlandroid


讓對象根據預設的程序運動,如讓一個三角形旋轉能夠有效地讓人引發注意,可是若是你但願可讓OpenGL ES與用戶交互呢?讓你的OpenGL ES應用能夠與觸摸交互的關鍵點在於,拓展你的GLSurfaceView的實現,覆寫onTouchEvent()方法來監聽觸摸事件。ide

這節課將會向你展現如何監聽觸摸事件,讓用戶旋轉一個OpenGL ES對象。this


一). 配置觸摸監聽器spa

爲了讓你的OpenGL ES應用響應觸摸事件,你必須實如今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.setAngle(
                    mRenderer.getAngle() +
                    ((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);
}

二). 公開旋轉角度rest

上述樣例代碼須要你公開旋轉的角度,方法是在你的渲染器中添加一個共有成員。因爲渲染器代碼運行在一個獨立的線程中(非主UI線程),你必須將你的這個公共變量聲明爲volatile。請看下面的代碼:code

public class MyGLRenderer implements GLSurfaceView.Renderer {
    ...
    public volatile float mAngle;

三). 應用旋轉htm

爲了應用觸摸輸入所致使的旋轉,註釋掉建立一個旋轉角度的代碼,而後添加mAngle,該變量包含了輸入所致使的角度:

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);
}

當你完成了上述的步驟,運行這個程序並用你的手指在屏幕上拖動,來旋轉三角形:

圖1. 由觸摸輸入所旋轉的三角形(圓形表明了當前觸摸位置)

相關文章
相關標籤/搜索