Saturday, 16 November 2013

Drawing Circle in Java Using 8-way Symmetry

Beginning with the equation the circle:
We can solve for 'y' in term of 'x':

and use this to compute the pixel of the circle.
But in that case, however, we will be neglecting the facts that a circle is symmetric to both the x-axis and y-axis. Thus we can draw only one of the quadrant of the circle and mirror it on the other quadrant to get the full circle.

We can further optimize our circle drawing algorithm by exploiting the 8 way symmetry in the circle by taking all possible combinations of x and y as shown below:
(+x,+y)(+x,-y)(-x,+y)(-x,-y)(+y,+x)(+y,-x)(-y,+x)(-y,-x)


Java Code for drawing circle using above 8-way symmetry:

import java.awt.Graphics;
import javax.swing.JFrame;

public class Circle extends JFrame{

	int xCenter,yCenter,radius;
	public Circle() {
		xCenter = 150;
		yCenter = 150;
		radius = 50;
	}
	public static void main(String[] args) {
		Circle obj = new Circle();
		obj.setSize(300, 300);
		obj.setVisible(true);
		
	}
	
	public void paint (Graphics g) {
		
		int y= yCenter ,x;
		
		g.drawLine(0, 0, 300, 300);
		g.drawLine(0, 300, 300, 0);
		g.drawLine(0, 150, 300, 150);
		g.drawLine(150, 0, 150, 300);
		
		while(y<(yCenter+radius/Math.sqrt(2))) {
			x=(int)Math.sqrt(Math.pow(radius, 2)-Math.pow(y-yCenter,2)) + xCenter; 
			g.drawRect(x, y, 1, 1);
			g.drawRect(300-x, y, 1, 1);
			g.drawRect(x, 300-y, 1, 1);
			g.drawRect(300-x,300- y, 1, 1);
			g.drawRect( y,300-x ,1, 1);
			g.drawRect(300-y,x ,1, 1);
			g.drawRect(y, x,1, 1);
			g.drawRect(300-y,300- x, 1, 1);
			y++;
		}
	}

}

No comments:

Post a Comment