Android---OpenGLES之响应触屏事件

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

创新互联是一家专业提供兴安企业网站建设,专注与成都网站制作、成都做网站、H5技术、小程序制作等业务。10年已为兴安众多企业、政府机构等服务。创新互联专业的建站公司优惠进行中。

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

设置触碰监听器

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

 
 
 
  1. @Override 
  2.   public boolean onTouchEvent(MotionEvent e) { 
  3.   // MotionEvent reportsinput details from the touch screen 
  4.   // and other inputcontrols. In this case, you are only 
  5.   // interested in eventswhere the touch position changed. 
  6.   float x = e.getX(); 
  7.   float y = e.getY(); 
  8.   switch (e.getAction()) { 
  9.   case MotionEvent.ACTION_MOVE: 
  10.   float dx = x - mPreviousX; 
  11.   float dy = y - mPreviousY; 
  12.   // reverse direction of rotation above the mid-line 
  13.   if (y > getHeight() / 2) { 
  14.   dx = dx * -1 ; 
  15.   } 
  16.   // reverse direction of rotation to left of the mid-line 
  17.   if (x < getWidth() / 2) { 
  18.   dy = dy * -1 ; 
  19.   } 
  20.   mRenderer.mAngle += (dx + dy) * TOUCH_SCALE_FACTOR; // = 180.0f /320 
  21.   requestRender(); 
  22.   } 
  23.   mPreviousX = x; 
  24.   mPreviousY = y; 
  25.   return true; 
  26.   } 

注意,计算旋转的角度之后,这个方法调用了requestRender()方法来告诉渲 染器,到了渲染帧的时候了。上例中所使用的方法是最有效的,只有在有旋转变化时,帧才会被重绘。但是要想只在数据变化的时候,才请求渲染器重绘,就要使用 setRenderMode()方法来设置绘制模式。

 
 
 
  1. publicMyGLSurfaceView(Context context){ 
  2.   ... 
  3.   // Render the view onlywhen there is a change in the drawing data 
  4.   setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); 
  5.   } 

暴露旋转的角度

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

 
 
 
  1. publicclassMyGLRendererimplementsGLSurfaceView.Renderer{ 
  2.   ... 
  3.   public volatile float mAngle; 

应用旋转

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

 
 
 
  1. publicvoidonDrawFrame(GL10 gl){ 
  2.   ... 
  3.   // Create a rotation forthe triangle 
  4.   // long time =SystemClock.uptimeMillis() % 4000L; 
  5.   // float angle = 0.090f *((int) time); 
  6.   Matrix.setRotateM(mRotationMatrix, 0, mAngle, 0, 0, -1.0f); 
  7.   // Combine the rotationmatrix with the projection and camera view 
  8.   Matrix.multiplyMM(mMVPMatrix, 0, mRotationMatrix, 0, mMVPMatrix, 0); 
  9.   // Draw triangle 
  10.   mTriangle.draw(mMVPMatrix); 
  11.   } 

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

本文题目:Android---OpenGLES之响应触屏事件
标题URL:http://www.zyruijie.cn/qtweb/news12/8362.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联