// Squares Union // Draw two squares, emphasizing their union import java.applet.*; import java.awt.*; import java.lang.Math; import TransformableSquare; public class SquaresUnion extends SquaresApplet { public void init() { this.setBackground(Color.white); this.setForeground(Color.black); update(getGraphics()); // force window create square1 = new TransformableSquare(188, imageBufferSize.height/2, 210); square1.rotate(2 * Math.PI * 45 / 360); square2 = new TransformableSquare(260, imageBufferSize.height/2, 160); 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.scale(.5); square2.scale(.5); g.setColor(getBackground()); g.fillPolygon(square1.getPolygon()); g.fillPolygon(square2.getPolygon()); // restore the squares square1.scale(2); square2.scale(2); // draw a couple of circles in the middle of squares g.setColor(getForeground()); g.fillOval(square1.center.x - 10, square1.center.y - 10, 19, 19); g.fillOval(square2.center.x - 10, square2.center.y - 10, 19, 19); // check how close the squares are int distanceSquared = (square1.center.x - square2.center.x) * (square1.center.x - square2.center.x) + (square1.center.y - square2.center.y) * (square1.center.y - square2.center.y); // if they're close enough, draw a line between them. if (distanceSquared < (square1.scaleFactor + square2.scaleFactor) * (square1.scaleFactor + square2.scaleFactor) / 16) { // Cruft below is for drawing a thick line between two points. // First, figure out which distance is bigger. int xdistance, ydistance; xdistance = (square1.center.x - square2.center.x); if (xdistance < 0) xdistance = -xdistance; ydistance = (square1.center.y - square2.center.y); if (ydistance < 0) ydistance = -ydistance; // move one point at a time along the longer axis, drawing // lines along the way. if (xdistance > ydistance) { int x, dx; float y, dy; dx = (square1.center.x < square2.center.x) ? 1 : -1; dy = (float)ydistance / (float)xdistance; if (square1.center.y > square2.center.y) dy = -dy; for (x = square1.center.x, y = square1.center.y; x != square2.center.x; x += dx, y += dy) g.drawLine(x, Math.round(y) - 3, x, Math.round(y) + 3); } else { float x, dx; int y, dy; dy = (square1.center.y < square2.center.y) ? 1 : -1; dx = (float)xdistance / (float)ydistance; if (square1.center.x > square2.center.x) dx = -dx; for (x = square1.center.x, y = square1.center.y; y != square2.center.y; x += dx, y += dy) g.drawLine(Math.round(x) - 3, y, Math.round(x) + 3, y); } } repaint(); } }