科赫雪花分形的C语言实现!
- 4阶科赫雪花分形
- Windows下的代码实现:
4阶科赫雪花分形
链接: link.
Windows下的代码实现:
仅贴出了窗口过程函数。
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{static int cxClient, cyClient;HDC hdc;PAINTSTRUCT ps;POINT pt;LONG x, y;const double SIZE = 500;const int ORDER = 4; // 科赫曲线阶数switch (message){case WM_CREATE:cxClient = LOWORD(lParam);cyClient = HIWORD(lParam);return 0;case WM_SIZE:cxClient = LOWORD(lParam);cyClient = HIWORD(lParam);return 0;case WM_PAINT:hdc = BeginPaint(hwnd, &ps);x = cxClient / 2;y = cyClient / 2;pt.x = x - SIZE / 2;pt.y = y - sqrt(3.0) * SIZE / 6.0;pt = FractalLine(hdc, pt, SIZE, 0.0, ORDER);pt = FractalLine(hdc, pt, SIZE, -2.0 * PI / 3.0, ORDER);pt = FractalLine(hdc, pt, SIZE, 2.0 * PI / 3.0, ORDER);EndPaint(hwnd, &ps);return 0;case WM_DESTROY:PostQuitMessage(0);return 0;}return DefWindowProc(hwnd, message, wParam, lParam);
}POINT PolarLine(HDC hdc, const POINT& pt, double r, double theta)
{return PolarLine(hdc, pt.x, pt.y, r, theta);
}POINT PolarLine(HDC hdc, LONG x, LONG y, double r, double theta)
{POINT pt;pt.x = x + r * cos(theta) + 0.5; // 0.5为四舍五入修正!!!pt.y = y - r * sin(theta) + 0.5;MoveToEx(hdc, x, y, NULL);LineTo(hdc, pt.x, pt.y);return pt;
}POINT FractalLine(HDC hdc, POINT pt, double r, double theta, int order)
{if (order == 0)return PolarLine(hdc, pt, r, theta);else{pt = FractalLine(hdc, pt, r / 3.0, theta, order - 1);pt = FractalLine(hdc, pt, r / 3.0, theta + PI / 3.0, order - 1);pt = FractalLine(hdc, pt, r / 3.0, theta - PI / 3.0, order - 1);return FractalLine(hdc, pt, r / 3.0, theta, order - 1);}
}