Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I draw a filled circle with OpenGL ES on iPhone?

Tags:

ios

opengl-es

How do I draw a filled circle with openGl on iPhone ?

I've found many solutions but none of them work. Probably because there are many ways to do it. But what's the method with shortest code ?

like image 437
aneuryzm Avatar asked Dec 01 '22 05:12

aneuryzm


1 Answers

For a truly smooth circle, you're going to want a custom fragment shader. For example, the following vertex shader:

 attribute vec4 position;
 attribute vec4 inputTextureCoordinate;

 varying vec2 textureCoordinate;

 void main()
 {
    gl_Position = position;
    textureCoordinate = inputTextureCoordinate.xy;
 }

and fragment shader:

 varying highp vec2 textureCoordinate;

 const highp vec2 center = vec2(0.5, 0.5);
 const highp float radius = 0.5;

 void main()
 {
     highp float distanceFromCenter = distance(center, textureCoordinate);
     lowp float checkForPresenceWithinCircle = step(distanceFromCenter, radius);

     gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0) * checkForPresenceWithinCircle;     
 }

will draw a smooth red circle within a square that you draw to the screen. You'll need to supply vertices for your square to the position attribute and coordinates that range from 0.0 to 1.0 in X and Y to the inputTextureCoordinate attribute, but this will draw a circle that's as sharp as your viewport's resolution allows and do so very quickly.

like image 112
Brad Larson Avatar answered Dec 06 '22 00:12

Brad Larson