科赫曲線(Koch Curve)是典型分形圖形,又稱雪花曲線。構造規則:
遞歸深度越深,曲線越複雜,長度趨近無限,但面積有限。
/**
* 繪製科赫曲線
* @param x1,y1 起點
* @param x2,y2 終點
* @param depth 遞歸深度(0 僅畫直線)
*/
public void drawKoch(int x1, int y1, int x2, int y2, int depth, Graphics g) {
if (depth <= 0) {
g.drawLine(x1, y1, x2, y2);
return;
}
// 三等分點
double x11 = (2 * x1 + x2) / 3.0;
double y11 = (2 * y1 + y2) / 3.0;
double x22 = (x1 + 2 * x2) / 3.0;
double y22 = (y1 + 2 * y2) / 3.0;
// 頂點(向外凸出 60 度)
double x33 = (x11 + x22) / 2 - Math.sqrt(3) * (y11 - y22) / 2;
double y33 = (y11 + y22) / 2 + Math.sqrt(3) * (x22 - x11) / 2;
// 遞歸繪製四段
drawKoch(x1, y1, (int)x11, (int)y11, depth - 1, g);
drawKoch((int)x11, (int)y11, (int)x33, (int)y33, depth - 1, g);
drawKoch((int)x33, (int)y33, (int)x22, (int)y22, depth - 1, g);
drawKoch((int)x22, (int)y22, x2, y2, depth - 1, g);
}
import javax.swing.*;
import java.awt.*;
public class KochSnowflake extends JPanel {
private int depth = 4; // 遞歸深度
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
int w = getWidth(), h = getHeight();
// 正三角形三邊
int cx = w / 2, cy = h / 2;
int size = Math.min(w, h) / 2;
int x1 = cx, y1 = cy - size;
int x2 = cx - (int)(size * Math.sqrt(3) / 2), y2 = cy + size / 2;
int x3 = cx + (int)(size * Math.sqrt(3) / 2), y3 = cy + size / 2;
drawKoch(x1, y1, x2, y2, depth, g);
drawKoch(x2, y2, x3, y3, depth, g);
drawKoch(x3, y3, x1, y1, depth, g);
}
// 上述 drawKoch 方法放這裡...
public static void main(String[] args) {
JFrame f = new JFrame("Koch Snowflake - Depth 4");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new KochSnowflake());
f.setSize(800, 800);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
z = z^2 + c,著色呈現。Graphics2D 開啟抗鋸齒:g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)。GeneralPath,一次 draw 減少繪圖呼叫。