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:
- 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.
- 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.
- Use a fragment shader.
But how do I implement them?
I definitely do not recommend rendering a circle through geometry. It has two major disadvantages:
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:
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.
This is a modified version of the above answer. It also includes the code to color the circle as well. Most of the functions are used as OpenGL ES1 though. Mind the naming conventions of class toilet, LOL. If you need the code of other classes where I render OpenGL as well, let me know.
https://gist.github.com/beetsolutions/9c343f86ec44987de4550cada118e560
You can find a complete working example here: https://github.com/beetsolutions/opengl_circle
Works perfectly and well optimised
One major flaw I noticed in 'goal's post: You can't change the position of the circle.
Here is the fix. Notice the end of the first two lines in the 'for' loop.
If you want to create geometry for the circle, do something like this:
Then you can draw using glDrawArrays() either as:
.