这边我们介绍一下利用windows编程如何来画五角星,下面主要介绍了3种与五角星相关图形的画法:
1.正常的五角星
代码如下:
#include
#include
#include
const double PI = 3.1415926;
LRESULT CALLBACK WndProc(
HWND hwnd, // handle to window
UINT uMsg, // message identifier
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
);
int WINAPI WinMain(
HINSTANCE hInstance, // handle to current instance
HINSTANCE hPrevInstance, // handle to previous instance
LPSTR lpCmdLine, // command line
int nCmdShow // show state
)
{
WNDCLASS wndclass;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hInstance = hInstance;
wndclass.lpfnWndProc = WndProc;
wndclass.lpszClassName = "我的窗口";
wndclass.lpszMenuName = NULL;
wndclass.style = CS_HREDRAW | CS_VREDRAW;
RegisterClass(&wndclass); //注册窗口类
HWND hwnd;
hwnd = CreateWindow("我的窗口", "窗口", WS_OVERLAPPEDWINDOW,
0, 0, 640, 480, NULL, NULL, hInstance, NULL);
ShowWindow(hwnd, SW_SHOWNORMAL);
UpdateWindow(hwnd);
MSG Msg;
while(GetMessage(&Msg, NULL, 0, 0))
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
return 0;
}
LRESULT CALLBACK WndProc(
HWND hwnd, // handle to window
UINT uMsg, // message identifier
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
)
{
HDC hdc;
PAINTSTRUCT ps;
HPEN hpen;
int r = 100;
switch(uMsg)
{
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
hpen = (HPEN)GetStockObject(BLACK_PEN);
SelectObject(hdc, hpen);
MoveToEx(hdc, 200 , 200 - r, NULL);
int k;
for(k=2; k<12; k=k+2)
{
LineTo(hdc, (int)(200 + r * cos((90-72*k)*PI/180)), (int)(200 - r * sin((90-72*k)*PI/180)));
}
EndPaint(hwnd, &ps);
DeleteObject(hpen);
break;
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
return 0;
}
关键代码如下:
int R = 100;
double r = R * sin(18*PI/180) / sin(54*PI/180);
MoveToEx(hdc, 200, 200 - R, NULL);
int k;
for(k=1; k<6; k++)
{
LineTo(hdc, (int)(200 + r * cos((126-72*k)*PI/180)), (int)(200 - r*sin((126-72*k)*PI/180)));
LineTo(hdc, (int)(200 + R * cos((90-72*k)*PI/180)), (int)(200 - R * sin((90-72*k)*PI/180)));
}
3.带边框的五角星
关键代码如下:
int k;
for(k=2; k<11; k=k+2)
{
LineTo(hdc, (int)(200 + r * cos((90-72*k)*PI/180)), (int)(200 - r * sin((90-72*k)*PI/180)));
}
for(k=1; k<6; k++)
{
LineTo(hdc, (int)(200 + r * cos((90-72*k)*PI/180)), (int)(200 - r * sin((90-72*k)*PI/180)));
}
4.总结:
实现画五角星最关键的是,要能够根据一个点的坐标,计算出其他所有点的坐标。剩下的画图只是简单的事情。