How to draw basic circle in OpenGL ES 2.0 Android

后端 未结 5 1267
时光取名叫无心
时光取名叫无心 2020-12-05 05:36

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

5条回答
  •  再見小時候
    2020-12-05 06:14

    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.

提交回复
热议问题