//支持的初始直线水平角度为60 的倍数, 交换起点与终点坐标可改变生成方向 void Koch(CDC *pDC, int x1, int y1, int x2, int y2, int n) { if (n > 0) { double k = 1.0*(y2 - y1) / (x2 - x1); int x3 = (x2 - x1) / 3; int y3 = (y2 - y1) / 3; Koch(pDC, x1, y1, x1 + x3, y1 + y3, n - 1); Koch(pDC, x2 - x3, y2 - y3, x2, y2, n - 1); if (abs(k) <= 1e-6) { Koch(pDC, x1 + x3, y1, x1 + x3 + x3 / 2, y1 + sqrt(3.0) / 2 * x3, n - 1); Koch(pDC, x1 + x3 + x3 / 2, y1 + sqrt(3.0) / 2 * x3, x2 - x3, y1, n - 1); } else if (k > 0) { Koch(pDC, x1, y2 - y3, x2 - x3, y2 - y3, n - 1); Koch(pDC, x1 + x3, y1 + y3, x1, y2 - y3, n - 1); } else { Koch(pDC, x1 + x3, y1 + y3, x2, y1 + y3, n - 1); Koch(pDC, x2, y1 + y3, x2 - x3, y2 - y3, n - 1); } } else { pDC->MoveTo(x1, y1); pDC->LineTo(x2, y2); } }
调用:
int k = 4; //递归的深度 CPen pen, *oldpen; pen.CreatePen(PS_SOLID, 1, RGB(255, 0,0 )); oldpen = pDC->SelectObject(&pen); Koch(pDC, 800, 150, 440, 150, k); pen.DeleteObject(); pen.CreatePen(PS_SOLID, 1, RGB(0, 255, 0)); pDC->SelectObject(&pen); Koch(pDC, 440, 200, 800, 200, k); pen.DeleteObject(); pen.CreatePen(PS_SOLID, 1, RGB(0, 0, 255)); pDC->SelectObject(&pen); Koch(pDC, 200, 100, 300, 275, k); Koch(pDC, 400, 100, 200, 100, k); Koch(pDC, 300, 275, 400, 100, k); pen.DeleteObject(); pDC->SelectObject(oldpen);
递归4次的效果图如下: