Thursday, October 26, 2017

rendering - Drawing a circle in OpenGL ES Android, squiggly boundaries


I am new to OpenGL ES and facing a hard time drawing a circle on my GLSurfaceView. Here's what I have so far.


The circle class


public class MyGLBall {

private int points=40;
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();
}

}

I couldn't retrieve the screenshot of my image but here's what it looks like enter image description here


As you can see the border has crests and troughs thereby rendering it squiggly, which I do not want. All I want is a simple curve.



Answer



I can't imagine how your code would produce the image you linked. I could however, imagine how it might produce an image like this:



enter image description here


With flat sides. So really what you want to do is increase the number of sides. Try setting:


private int points=40;

to something larger like


private int points=360;

If you wanted a loop like your image instead of a circle you can do something like this:


public float[] DrawLoop(float centerX, float centerY, float sides, float innerRadius, float outerRadius) {
float[] vertices = new float[(sides+1)*4];

for (int i = 0; i <= sides; i+=4) {
verticies[i+0] = centerX + (sin(toRadians(360f * (i / sides))) * innerRadius);
verticies[i+1] = centerY - (cos(toRadians(360f * (i / sides))) * innerRadius);
verticies[i+2] = centerX + (sin(toRadians(360f * (i / sides))) * outerRadius);
verticies[i+3] = centerY - (cos(toRadians(360f * (i / sides))) * outerRadius);
}
return vertices;
}

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...