上一篇介紹了 OpenGL ES 能夠繪制的幾種基本幾何圖形:點,線,三角形。將分別介紹這幾種基本幾何圖形的例子。為方便起見,暫時在同一平面上繪制這些幾何圖形,在后面介紹完 OpenGL ES 的坐標系統和坐標變換后,再介紹真正的 3D 圖形繪制方法。
在 Android OpenGL ES 開發教程(7):創建實例應用 OpenGLDemos 程序框架 創建了示例應用的程序框架,并提供了一個“Hello World”示例。
為避免一些重復代碼,這里定義一個所有示例代碼的基類 OpenGLESActivity,其定義如下:
public class OpenGLESActivity extends Activity
implements IOpenGLDemo{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
mGLSurfaceView = new GLSurfaceView(this);
mGLSurfaceView.setRenderer(new OpenGLRenderer(this));
setContentView(mGLSurfaceView);
}
public void DrawScene(GL10 gl) {
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
// Clears the screen and depth buffer.
gl.glClear(GL10.GL_COLOR_BUFFER_BIT
| GL10.GL_DEPTH_BUFFER_BIT);
}
@Override
protected void onResume() {
// Ideally a game should implement onResume() and onPause()
// to take appropriate action when the activity looses focus
super.onResume();
mGLSurfaceView.onResume();
}
@Override
protected void onPause() {
// Ideally a game should implement onResume() and onPause()
// to take appropriate action when the activity looses focus
super.onPause();
mGLSurfaceView.onPause();
}
protected GLSurfaceView mGLSurfaceView;
}
OpenGL ES 內部存放圖形數據的 Buffer 有 COLOR ,DEPTH (深度信息)等,在繪制圖形只前一般需要清空 COLOR 和 DEPTH Buffer。
本例在屏幕上使用紅色繪制 3 個點。創建一個 DrawPoint 作為 OpenGLESActivity 的子類,并定義 3 個頂點的坐標:
public class DrawPoint extends OpenGLESActivity
implements IOpenGLDemo{
float[] vertexArray = new float[]{
-0.8f , -0.4f * 1.732f , 0.0f ,
0.8f , -0.4f * 1.732f , 0.0f ,
0.0f , 0.4f * 1.732f , 0.0f ,
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
...
}
下面為 DrawPoint 的 DrawScene 的實現:
public void DrawScene(GL10 gl) {
super.DrawScene(gl);
ByteBuffer vbb
= ByteBuffer.allocateDirect(vertexArray.length*4);
vbb.order(ByteOrder.nativeOrder());
FloatBuffer vertex = vbb.asFloatBuffer();
vertex.put(vertexArray);
vertex.position(0);
gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
gl.glPointSize(8f);
gl.glLoadIdentity();
gl.glTranslatef(0, 0, -4);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertex);
gl.glDrawArrays(GL10.GL_POINTS, 0, 3);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
http://wiki.jikexueyuan.com/project/opengl-es-guide/images/56.png" alt="" />
本例下載