// Squares Intersect // Draw two squares, then highlight their intersection import java.applet.*; import java.awt.*; import java.lang.Math; import TransformableSquare; public class SquaresIntersect extends SquaresApplet { public void init() { this.setBackground(Color.white); this.setForeground(Color.black); update(getGraphics()); // force window create square1 = new TransformableSquare(2*imageBufferSize.width/5, imageBufferSize.height/2, 4*imageBufferSize.width/9); square1.rotate(2 * Math.PI * 45 / 360); square2 = new TransformableSquare(3*imageBufferSize.width/5, imageBufferSize.height/2, 3*imageBufferSize.width/7); super.init(); redrawImage(); } // draw the image // roughly - two thick squares, the intersection is striped vertical lines public void redrawImage() { Graphics g = imageBuffer.getGraphics(); clearImageBuffer(); // draw two filled black squares g.setColor(getForeground()); g.fillPolygon(square1.getPolygon()); g.fillPolygon(square2.getPolygon()); // make smaller filled white squares inside square1.scalePixels(-10); square2.scalePixels(-10); g.setColor(getBackground()); g.fillPolygon(square1.getPolygon()); g.fillPolygon(square2.getPolygon()); // now paint vertical lines in the intersection g.setColor(getForeground()); // Find the smaller bounding box (well, not quite - but close) TransformableSquare smallerSquare; smallerSquare = (square1.scaleFactor < square2.scaleFactor ? square1 : square2); Rectangle bound = smallerSquare.getPolygon().getBoundingBox(); int x, y1, y2; // scan across the bounding box for (x = bound.x; x < bound.width + bound.x; x+=6) { y1 = bound.y; // scan down, looking for first intersection while (y1 < bound.height + bound.y && !(square1.inside(x, y1) && square2.inside(x, y1))) y1++; if (!(square1.inside(x, y1) && square2.inside(x, y1))) continue; // not found this time.. // scan down, looking for when we leave the intersection y2 = y1; while (y2 < bound.height + bound.y && (square1.inside(x, y2) && square2.inside(x, y2))) y2++; // draw a line inbetween g.fillRect(x-1, y1, 3, y2-y1); } // restore squares to original size square1.scalePixels(10); square2.scalePixels(10); repaint(); } }