How to draw basic circle in OpenGL ES 2.0 Android

Sơn Nguyễn picture Sơn Nguyễn · Aug 9, 2013 · Viewed 30.1k times · Source

I'm new in OpenGL ES 2, and I have read many topics about how to draw a circle in OpenGL ES 2 on Android. Based on Drawing Shapes and this code found on gamedev.net, I can draw triangles and quares, but I still don't know how to draw a circle. I now have three ways to draw a circle:

  1. Generate vertices in a circle and use glDrawArray( GL_LINES, ... ). Depending on how many vertices you generate this will yield a nice and crisp result.
  2. Use a pregenerated texture of a circle (with alpha transparency) and map it on a quad. This will result in very smooth graphics and allow for a ´thick´ circle, but it will not be as flexible: Even with mipmapping, you'll want your texture to be about the same size you are rendering the quad.
  3. Use a fragment shader.

But how do I implement them?

Answer

Marcel Jöstingmeier picture Marcel Jöstingmeier · Dec 24, 2014

I definitely do not recommend rendering a circle through geometry. It has two major disadvantages:

  1. It is slow. If you want to get acceptable accuracy you need a lot of vertices and any of these vertices need to be processed in the shader. For a real circle you need as many vertices as your circle have pixels.
  2. It is not really flexible. Having different circles, styling and colring them is hard to master.

There is another method, which I personally use in every graphics API. Rendering at least a triangle or a sqare/quad and use the fragment-shader to only make the disired (based on a equation) pixel visible. It is very easy to understand. It is flexible and fast. It needs blending, but this is not really hard to get to work.

Steps:

Initialize your buffers with data. You need a vertex-buffer for the vertices, an index-buffer for the indices if you're a using a square geometry, and a textureCoord-buffer for your texture coordinates. For a square I recommend using -1.0 as the lowest and 1.0 as the highest texture coordinate, because then you are able to use the unit circle equation.

In your fragment-shader, use something like this:

if ((textureCoord.x * textureCoord.x) + (textureCoord.y * textureCoord.y) <= 1.0)
{
    // Render colored and desired transparency
}
else
{
    // Render with 0.0 in alpha channel
}

While (textureCoord.x * textureCoord.x) + (textureCoord.y * textureCoord.y) <= 1.0 is the inequality, because you need a circle, you have to render every pixel within that range, not just the border. You can change this so that it gives you the desired output.

And that is it. Not very complex to implement, so I don't offer any basic rendering code here. All you need happens within the fragment-shader.