效果图:
代码:
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
@SuppressWarnings("serial")
public class Triangles extends JFrame {
public static void main(String[] args) {
new Triangles();
}
public Triangles() {
super("Triangles, count = 50");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setSize(400,300);
add("Center", new CvTriangles());
setVisible(true);
}
}
@SuppressWarnings("serial")
class CvTriangles extends Canvas {
private int maxX;
private int maxY;
private int minMaxXY;
private int centerX;
private int centerY;
private void initgr() {
Dimension d = getSize();
maxX = d.width - 1;
maxY = d.height - 1;
minMaxXY = Math.min(maxX, maxY);
centerX = maxX / 2;
centerY = maxY / 2;
}
private int iX(float x) {
return Math.round(x);
}
private int iY(float y) {
return maxY - Math.round(y);
}
public void paint(Graphics g) {
initgr();
float side = 0.95F * minMaxXY, sideHalf = 0.5F * side,
h = sideHalf * (float)Math.sqrt(3),
xA, yA, xB, yB, xC, yC,
xA1, yA1, xB1, yB1, xC1, yC1,
p, q;
q = 0.05F;
p = 1 - q;
xA = centerX - sideHalf;
yA = centerY - 0.5F * h;
xB = centerX + sideHalf;
yB = yA;
xC = centerX;
yC = centerY + 0.5F * h;
for (int i = 0; i < 50; i++) {
g.drawLine(iX(xA), iY(yA), iX(xB), iY(yB));
g.drawLine(iX(xB), iY(yB), iX(xC), iY(yC));
g.drawLine(iX(xC), iY(yC), iX(xA), iY(yA));
// move to left by 0.1 * sideHalf
xA1 = p * xA + q * xB;
yA1 = p * yA + q * yB;
xB1 = p * xB + q * xC;
yB1 = p * yB + q * yC;
xC1 = p * xC + q * xA;
yC1 = p * yC + q * yA;
xA = xA1; yA = yA1;
xB = xB1; yB = yB1;
xC = xC1; yC = yC1;
}
}
}