import java.awt.*; import java.awt.event.*; import java.applet.*; /* Animation of the really simple "test each pixel to see if it is in the polygon" algorithm for drawing filled polygons. */ public class poly extends BigPixelApplet{ public void init() { super.init(); canvas.addMouseListener(new MyAdapter()); canvas.addMouseMotionListener(new RubberLine()); } Polygon p = new Polygon(); //polygon that is being created interactively boolean creating = false; //have we started the polygon yet? int startx, starty; //start of rubber line int endx, endy; //end of rubber line public void run() { drawPolygon(p); } /** Implements a rubber band line that follows cursor while button is down */ class RubberLine extends MouseMotionAdapter { public void mouseDragged(MouseEvent e) { Graphics g = canvas.getGraphics(); g.setXORMode(Color.cyan); g.drawLine(toScreenX(startx),toScreenY(starty),toScreenX(endx),toScreenY(endy)); endx = fromScreenX(e.getX()); endy = fromScreenY(e.getY()); g.drawLine(toScreenX(startx),toScreenY(starty),toScreenX(endx),toScreenY(endy)); } public void mouseMoved(MouseEvent e) { if (creating) { mouseDragged(e); } } } class MyAdapter extends MouseAdapter { public void mousePressed(MouseEvent e) { startx = fromScreenX(e.getX()); starty = fromScreenY(e.getY()); endx = startx; endy = starty; if (startx == p.xpoints[0] && starty == p.ypoints[0]){ //polygon closed creating = false; canvas.setPolygon(p); begin();//this calls run() in another thread to do the animation } else { if (!creating) { creating = true; p = new Polygon(); } p.addPoint(startx, starty); } } } /* These three variables contain the state of the algorithm */ int x; int y; int count; public String showState() { return "x = " + x + " y = " + y + " count = " + count; } void drawPolygon(Polygon p){ //create array of all the edges Edge[] edges = new Edge[p.npoints]; edges[0] = new Edge(p.xpoints[p.npoints-1],p.ypoints[p.npoints-1],p.xpoints[0],p.ypoints[0]); for (int i = 1; i < p.npoints; i++) { edges[i] = new Edge(p.xpoints[i-1],p.ypoints[i-1],p.xpoints[i],p.ypoints[i]); } Rectangle r = p.getBounds(); for (y = r.y; y < r.y + r.height; y++) { for (x = r.x; x < r.x + r.width; x++) { count = 0; for (int i = 0; i < p.npoints; i++) { if (edges[i].rayIntersect(x,y)) count++; } if (count % 2 == 1) { drawPixel(x,y); } if (step()) return; } } } }