Thursday, March 23, 2017

How to draw a smooth circle in Android using OpenGL?


I am learning about OpenGL API on Android. I just drew a circle. Below is the code I used.


public class MyGLBall {


private int points=360;
private float vertices[]={0.0f,0.0f,0.0f};
private FloatBuffer vertBuff;


//centre of circle

public MyGLBall(){

vertices=new float[(points+1)*3];

for(int i=3;i<(points+1)*3;i+=3){
double rad=(i*360/points*3)*(3.14/180);
vertices[i]=(float)Math.cos(rad);
vertices[i+1]=(float) Math.sin(rad);
vertices[i+2]=0;
}
ByteBuffer bBuff=ByteBuffer.allocateDirect(vertices.length*4);
bBuff.order(ByteOrder.nativeOrder());
vertBuff=bBuff.asFloatBuffer();
vertBuff.put(vertices);

vertBuff.position(0);


}

public void draw(GL10 gl){
gl.glPushMatrix();
gl.glTranslatef(0, 0, 0);
// gl.glScalef(size, size, 1.0f);
gl.glColor4f(1.0f,1.0f,1.0f, 1.0f);

gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glPopMatrix();
}

}

It is actually taken directly from here The circle looks pretty good. But now I want to make the boundary of the circle smooth. What changes do I need to make to the code? Or do I need to use some other technique for drawing the circle?



Thanks.



Answer



With polygon-based graphics, the only option you have to better approximate a circle is to subdivide further. 720 triangles will result in a smoother circle, but 1440 will give you an even smoother circle, but 2880...


A perfect circle, created using polygons, would require an infinite amount of infinitesimally small polygon sections (in other words, it just isn't possible, in theory). Practically, however, if you subdivide enough times, you may reach a point where the length of the polygon section is equal to or smaller in size than a pixel, meaning that, for purposes of your framebuffer, you have achieved a "perfect" circle.


The other option, of course, is to cheat: render a flat quadrilateral oriented perpendicular to the camera, and texture it with an image of a sphere. 2 triangles, 1 texture of sufficient resolution: smooth circle, and a hell of a lot less vertices for your GPU to worry about.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...