Android OpenGL ES 开发教程(10):绘制线段Line Segment

jerry OpenGL ES 2015年11月25日 收藏

创建一个DrawLine Activity,定义四个顶点:

  1. float vertexArray[] = {
  2. -0.8f, -0.4f * 1.732f, 0.0f,
  3. -0.4f, 0.4f * 1.732f, 0.0f,
  4. 0.0f, -0.4f * 1.732f, 0.0f,
  5. 0.4f, 0.4f * 1.732f, 0.0f,
  6. };

分别以三种模式GL_LINES,GL_LINE_STRIP,GL_LINE_LOOP 来绘制直线:

  1. public void DrawScene(GL10 gl) {
  2. super.DrawScene(gl);
  3.  
  4. ByteBuffer vbb
  5. = ByteBuffer.allocateDirect(vertexArray.length*4);
  6. vbb.order(ByteOrder.nativeOrder());
  7. FloatBuffer vertex = vbb.asFloatBuffer();
  8. vertex.put(vertexArray);
  9. vertex.position(0);
  10.  
  11. gl.glLoadIdentity();
  12. gl.glTranslatef(0, 0, -4);
  13.  
  14. gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
  15.  
  16. gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertex);
  17. index++;
  18. index%=10;
  19. switch(index){
  20. case 0:
  21. case 1:
  22. case 2:
  23. gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
  24. gl.glDrawArrays(GL10.GL_LINES, 0, 4);
  25. break;
  26. case 3:
  27. case 4:
  28. case 5:
  29. gl.glColor4f(0.0f, 1.0f, 0.0f, 1.0f);
  30. gl.glDrawArrays(GL10.GL_LINE_STRIP, 0, 4);
  31. break;
  32. case 6:
  33. case 7:
  34. case 8:
  35. case 9:
  36. gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f);
  37. gl.glDrawArrays(GL10.GL_LINE_LOOP, 0, 4);
  38. break;
  39. }
  40.  
  41. gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
  42.  
  43. }

这里index 的目的是为了延迟一下显示(更好的做法是使用固定时间间隔)。前面说过GLSurfaceView 的渲染模式有两种,一种是连续不断的更新屏幕,另一种为on-demand ,只有在调用requestRender() 在更新屏幕。 缺省为RENDERMODE_CONTINUOUSLY 持续刷新屏幕。

OpenGLDemos 使用的是缺省的RENDERMODE_CONTINUOUSLY持续刷新屏幕 ,因此Activity的drawScene 会不断的执行。中屏幕上顺序以红,绿,蓝色显示LINES, LINE_STRIP,LINE_LOOP。