在上篇文章,我們能夠配置好基本的Android OpenGL 使用的環境。但是如果我們不了解OpenGL ES如何定義圖像的一些基本知識就使用OpenGL ES進行繪圖還是有點棘手的。所以能夠在OpenGL ES的View里面定義要繪制的形狀是進行高端繪圖操作的第一步。
本文主要做的事情就是為了講解Android設備屏幕相關的OpenGL ES坐標系統,定義形狀,形狀面的基礎知識,以及定義三角形和正方形。
一、定義三角形
OpenGL ES允許你使用三維空間坐標系定義繪制的圖像,所以你在繪制一個三角形之前必須要先定義它的坐標。在OpenGL中,這樣做的典型方法是為坐標定義浮點數的頂點數組。
為了獲得最大的效率,可以將這些坐標寫入ByteBuffer,並傳遞到OpenGL ES圖形管道進行處理。
public class Triangle {
private FloatBuffer vertexBuffer;
// number of coordinates per vertex in this array
static final int COORDS_PER_VERTEX = 3;
static float triangleCoords[] = { // in counterclockwise order:
0.0f, 0.622008459f, 0.0f, // top
-0.5f, -0.311004243f, 0.0f, // bottom left
0.5f, -0.311004243f, 0.0f // bottom right
};
// Set color with red, green, blue and alpha (opacity) values
float color[] = { 0.63671875f, 0.76953125f, 0.22265625f, 1.0f };
public Triangle() {
// initialize vertex byte buffer for shape coordinates
ByteBuffer bb = ByteBuffer.allocateDirect(
// (number of coordinate values * 4 bytes per float)
triangleCoords.length * 4);
// use the device hardware's native byte order
bb.order(ByteOrder.nativeOrder());
// create a floating point buffer from the ByteBuffer
vertexBuffer = bb.asFloatBuffer();
// add the coordinates to the FloatBuffer
vertexBuffer.put(triangleCoords);
// set the buffer to read the first coordinate
vertexBuffer.position(0);
}
}
默認情況下,OpenGL ES采用坐標系,[0,0,0](X,Y,Z)指定GLSurfaceView框架的中心,[1,1,0]是框架的右上角,[ - 1,-1,0]是框架的左下角。 有關此坐標系的說明,請參閱OpenGL ES開發人員指南。
請注意,此圖形的坐標以逆時針順序定義。 繪圖順序非常重要,因為它定義了哪一面是您通常想要繪制的圖形的正面,以及背面。關於這塊相關的更多的內容,可以去查看一下相關的OpenGL ES 文檔。
二、定義正方形
可以看到,在OpenGL里面定義一個三角形很簡單。但是如果你想要得到一個更復雜一點的東西呢?比如一個正方形?能夠找到很多辦法來作到這一點,但是在OpenGL里面繪制這個圖形的方式是將兩個三角形畫在一起。
同樣,你應該以逆時針的順序為這兩個代表這個形狀的三角形定義頂點,並將這些值放在一個ByteBuffer中。 為避免定義每個三角形共享的兩個坐標兩次,請使用圖紙列表告訴OpenGL ES圖形管道如何繪制這些頂點。 這是這個形狀的代碼:
public class Square {
private FloatBuffer vertexBuffer;
private ShortBuffer drawListBuffer;
// number of coordinates per vertex in this array
static final int COORDS_PER_VERTEX = 3;
static float squareCoords[] = {
-0.5f, 0.5f, 0.0f, // top left
-0.5f, -0.5f, 0.0f, // bottom left
0.5f, -0.5f, 0.0f, // bottom right
0.5f, 0.5f, 0.0f }; // top right
private short drawOrder[] = { 0, 1, 2, 0, 2, 3 }; // order to draw vertices
public Square() {
// initialize vertex byte buffer for shape coordinates
ByteBuffer bb = ByteBuffer.allocateDirect(
// (# of coordinate values * 4 bytes per float)
squareCoords.length * 4);
bb.order(ByteOrder.nativeOrder());
vertexBuffer = bb.asFloatBuffer();
vertexBuffer.put(squareCoords);
vertexBuffer.position(0);
// initialize byte buffer for the draw list
ByteBuffer dlb = ByteBuffer.allocateDirect(
// (# of coordinate values * 2 bytes per short)
drawOrder.length * 2);
dlb.order(ByteOrder.nativeOrder());
drawListBuffer = dlb.asShortBuffer();
drawListBuffer.put(drawOrder);
drawListBuffer.position(0);
}
}
這個例子讓你了解用OpenGL創建更復雜的形狀的過程。 一般來說,您使用三角形的集合來繪制對象。下面的文章里面,將講述如何在屏幕上繪制這些形狀。