Sunday, July 1, 2018

How to Draw a Triangle in OpenGL ES (Android) — Step-by-Step Beginner Guide

Android apps are easily created using the android studio. Firstly you have to create an OpenGL ES environment to draw a shape such as a triangle. I referred to the developer.android.com site which is a good and extensive source of technical information.

If you're learning OpenGL ES on Android, the first thing everyone tries is drawing a triangle.

And yet…
👉 You either get a black screen
👉 Or nothing shows up
👉 Or the app crashes without explanation

In this guide, I’ll show you exactly how to draw a triangle in OpenGL ES, with working code and common mistakes to avoid.

What You’ll Learn Here

  • How OpenGL ES rendering works (basic idea)
  • How to define triangle vertices
  • How shaders work (simple explanation)
  • Working Android code to render a triangle
I had to download an android studio which happens fast and easy and I was good to go in half an hour or so. 

Step 1: Define Triangle Coordinates

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

👉 This defines a triangle in 3D space (x, y, z)

Step 2: Create Vertex Shader

String vertexShaderCode =
"attribute vec4 vPosition;" +
"void main() {" +
" gl_Position = vPosition;" +
"}";

👉 This shader tells OpenGL where to place the triangle

Step 3: Create Fragment Shader

String fragmentShaderCode =
"precision mediump float;" +
"void main() {" +
" gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);" +
"}";

👉 This makes the triangle red

Step 4: Draw the Triangle

GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3);

🖼️ Output

👉 You should now see a red triangle centered on screen

Common Mistakes (IMPORTANT)

1. Black Screen


  • Forgot to call glClear()
  • Shader failed to compile

2. Triangle Not Visible

  • Coordinates out of range (-1 to +1)
  • Wrong buffer setup

3. App Crash

  • Missing OpenGL context
  • Incorrect shader linking
There were problems I encountered esp with OpenGL ES environment. 

Pro Tip

If nothing shows:
👉 Always check shader compile logs — 90% of errors are there.


What Next?

Now that you can draw a triangle, try:

  • Drawing a square
  • Adding colors per vertex
  • Animating the triangle

Final Thoughts

This may look simple, but this triangle is the foundation of all 3D graphics—games, simulations, everything.

I have now created a sierpinski gasket where the triangles are subdivided upon clicking the screen.
Update:
You may want to read further about another app that divides the triangle into sierpinski gasket: