The following code draws a circle of particular diameter by setting the PIXELS falling inside the circle to a different RGB value. It involves simple co-ordinate geometry fundas. There are some approximations being taken.
_______________________________________________________________________________________________
import java.awt.image.*;
import javax.swing.*;
import javax.swing.JComponent.*;
public class circles extends JFrame {
public static void main(String args[]) {
double d=Double.parseDouble(args[0]);
int diameter= (int)d;
circles ca= new circles();
ca.drawCircle(diameter);
}
public void drawCircle(int diameter) {
int x=0,y=0,radius;
JFrame frame=new JFrame();
JLabel lab;
BufferedImage bi=new BufferedImage (diameter,diameter,BufferedImage.TYPE_BYTE_GRAY );
WritableRaster raster=bi.getRaster();
double [] iPix=new double [diameter*diameter];
if(diameter%2 == 1) {
diameter-=1;
}
radius=diameter/2;
for(int i=0;i
y=y%(radius);
}
else
{
y-=radius;
y=-y;
}
if((x*x+y*y)<=((radius)*(radius))) { iPix[i]=255; } else { iPix[i]=0; } }
raster.setPixels(0,0,diameter,diameter,iPix); lab=new JLabel(new ImageIcon(bi)); frame.add(lab);
frame.setVisible(true); frame.setSize(600,600);
}
}
_______________________________________________________________________________________________ _______________________________________________________________________________________________
compile the program as javac circles.java
run as java circles diameter_value
21 June, 2008
Draw a Circle in Java, the fundamental "pixels" way !
Subscribe to:
Post Comments (Atom)
0 readers commented:
Post a Comment