注:本文翻譯自Google官方的Android Developers Training文檔,譯者技術一般,由于喜愛安卓而產生了翻譯的念頭,純屬個人興趣愛好。
原文鏈接: 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 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); }
二). 公開旋轉角度
上述樣例代碼需要你公開旋轉的角度,方法是在你的渲染器中添加一個共有成員。由于渲染器代碼運行在一個獨立的線程中(非主UI線程),你必須將你的這個公共變量聲明為 volatile。請看下面的代碼:
public class MyGLRenderer implements GLSurfaceView.Renderer { ... public volatile float mAngle;
三). 應用旋轉
為了應用觸摸輸入所導致的旋轉,注釋掉創建一個旋轉角度的代碼,然后添加 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. 由觸摸輸入所旋轉的三角形(圓形代表了當前觸摸位置)
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
