Wednesday 16 December 2015

Draw a Square in Android OpenGL ES


Hello~

Continue previous tutorial, we already have created a renderer environment, now let's learn to draw primitives inside the renderer.

We will use triangle strip method to draw the square, if you don't know what is triangle strip, you google search it and try to understand it by your self.

First declare 4 vertices inside your Stage class constructor, add this code:

float vertices[] = {
-0.5f, -0.5f, 0.0f, //left-bottom
0.5f, -0.5f, 0.0f, //right-bottom
-0.5f, 0.5f, 0.0f, //left-top
0.5f, 0.5f, 0.0f, //right-top
};

After this declare a global private variable FloatBuffer and named it as vertexBuffer and add this code below the float vertices:

ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
vbb.order(ByteOrder.nativeOrder());
vertexBuffer = vbb.asFloatBuffer();
vertexBuffer.put(vertices);
vertexBuffer.position(0);

The code above is to converts the managed vertex buffer to one accessible in native space

Okay everything needed is prepared, now let's start drawing object inside the onDrawFrame

When start drawing object with OpenGL, your code need to start with gl.glPushMatrix(); and end with gl.glPopMatrix();

Next add this code between glPush and glPop Matrix:

gl.glClear(GLES10.GL_COLOR_BUFFER_BIT);
gl.glTranslatef(w / 2, h / 2, 0);
gl.glScalef(120, 100, 0);
gl.glColor4f(0, 1, 0, 1);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);

Here is some explanation of the OpenGL ES code, glTranslatef method is used to positioning the object, glScalef method is used to scale the size of the object, glColor4f method takes four arguments which is red, green, blue and alpha, alpha is used to adjust the transparency of the object. The method glVertexPointer introduces vertexBuffer as the current working vertex buffer. The method glDrawArrays is used to draw vertices off vertex buffers, the last argument from glDrawArrays method is the number of vertices we want to read from the array.

The final output will be like this:




Video Tutorial: Click here

No comments:

Post a Comment