Erfan Ahmed Emon - 1 year ago 149
Java Question

# Bresenham circle drawing algorithm implementation in Java

I've implemented Bresenham Circle drawing algorithm in Java. But the output is not correctly drawn! I can't find where the problem is.

My code and output image is given below. Any help is appreciated.

``````public void display(GLAutoDrawable drawable) {
final GL2 gl = drawable.getGL().getGL2();
gl.glBegin (GL2.GL_POINTS);
double x =0.0;
gl.glVertex2d(0.0,0.0);
gl.glVertex2d(x,y);
gl.glVertex2d(-x,y);
gl.glVertex2d(x,-y);
gl.glVertex2d(-x,-y);
gl.glVertex2d(y,x);
gl.glVertex2d(-y,x);
gl.glVertex2d(y,-x);
gl.glVertex2d(-y,-x);
double d = 5 - 4*radius;
while(x<y){
if(d<0){ //dE

x+=.01;
d+=(2*x + 3)*4;
}else{

x+=.01;
y-=.01;
d+=(2*x - 2*y +5)*4;
}
gl.glVertex2d(x,y);
gl.glVertex2d(-x,y);
gl.glVertex2d(x,-y);
gl.glVertex2d(-x,-y);
gl.glVertex2d(y,x);
gl.glVertex2d(-y,x);
gl.glVertex2d(y,-x);
gl.glVertex2d(-y,-x);

}
gl.glEnd();
}
``````

Notice that the original Bresenham's circle algorithm works only with integers. Since your update is `x_{n+1}=x_n+eps` you can modify your `y` update to

``````y_{n+1}^2 = y_n^2 - 2*eps*n-eps*eps
``````

The derivation is the same as the one given at the wiki page.

``````public void display(GLAutoDrawable drawable) {
final GL2 gl = drawable.getGL().getGL2();
gl.glBegin (GL2.GL_POINTS);
double x =0.0;
gl.glVertex2d(0.0,0.0);
gl.glVertex2d(x,y);
gl.glVertex2d(-x,y);
gl.glVertex2d(x,-y);
gl.glVertex2d(-x,-y);
gl.glVertex2d(y,x);
gl.glVertex2d(-y,x);
gl.glVertex2d(y,-x);
gl.glVertex2d(-y,-x);

double eps = .01;
double eps2 = eps*eps;
while(x<y){

y = Math.sqrt(y*y-2*eps*x-eps2);
x+= eps;
gl.glVertex2d(x,y);
gl.glVertex2d(-x,y);
gl.glVertex2d(x,-y);
gl.glVertex2d(-x,-y);
gl.glVertex2d(y,x);
gl.glVertex2d(-y,x);
gl.glVertex2d(y,-x);
gl.glVertex2d(-y,-x);

}
gl.glEnd();
}
``````

Result:

Be also careful of the aspect ratio. This algorithm works properly for ratio `1:1`. If, however, your aspect ratio is `a:b` your equation for the circle would become `x^2/a^2+y^2/b^2=r^2`. You can change the update accordingly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download