Android---OpenGL ES之響應(yīng)觸屏事件
像旋轉(zhuǎn)三角形那樣,讓對(duì)象根據(jù)預(yù)設(shè)的程序來(lái)移動(dòng),以便有助于獲取人們的關(guān)注,但是如 果想要讓你的OpenGL ES圖形跟用戶交互,應(yīng)該怎樣做呢?要讓你的OpenGL ES應(yīng)用程序能夠觸碰交互的關(guān)鍵是擴(kuò)展你的GLSurfaceView實(shí)現(xiàn),重寫(xiě)它的onTouchEvent()方法來(lái)監(jiān)聽(tīng)觸碰事件。
本文介紹如何監(jiān)聽(tīng)觸碰事件,讓用戶可以旋轉(zhuǎn)OpenGL ES對(duì)象。
設(shè)置觸碰監(jiān)聽(tīng)器
為了讓你的OpenGL ES應(yīng)用程序響應(yīng)觸碰事件,你必須在你GLSurfaceView類中實(shí)現(xiàn)onTouchEvent()事件。以下實(shí)現(xiàn)的示例顯示如何監(jiān)聽(tīng)MotionEvent.ACTION_MOVE事件,并把它們轉(zhuǎn)換成圖形旋轉(zhuǎn)的角度。
- @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;
- }
注意,計(jì)算旋轉(zhuǎn)的角度之后,這個(gè)方法調(diào)用了requestRender()方法來(lái)告訴渲 染器,到了渲染幀的時(shí)候了。上例中所使用的方法是最有效的,只有在有旋轉(zhuǎn)變化時(shí),幀才會(huì)被重繪。但是要想只在數(shù)據(jù)變化的時(shí)候,才請(qǐng)求渲染器重繪,就要使用 setRenderMode()方法來(lái)設(shè)置繪制模式。
- publicMyGLSurfaceView(Context context){
- ...
- // Render the view onlywhen there is a change in the drawing data
- setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
- }
暴露旋轉(zhuǎn)的角度
上例代碼要求你通過(guò)添加一個(gè)公共的成員變量,通過(guò)渲染器把旋轉(zhuǎn)的角度暴露出來(lái)。因?yàn)殇秩酒鞔a運(yùn)行在一個(gè)獨(dú)立于主用戶界面線程之外的線程中,所以你必須聲明一個(gè)公共變量,代碼如下:
- publicclassMyGLRendererimplementsGLSurfaceView.Renderer{
- ...
- public volatile float mAngle;
應(yīng)用旋轉(zhuǎn)
以下代碼完成由觸碰輸入所產(chǎn)生的旋轉(zhuǎn):
- 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);
- }
本文譯自:http://developer.android.com/training/graphics/opengl/touch.html