科赫雪花分形的C语言实现!

科赫雪花分形的C语言实现!

4阶科赫雪花分形

链接: link.
Alt

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);
	}
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值