C语言画会跳动的爱心
时间: 2023-07-04 19:05:34 浏览: 76
下面是一个使用C语言绘制跳动的爱心的示例代码。该代码使用了Windows API中的绘图函数,需要在Windows环境中运行。
```c
#include <windows.h>
#define PI 3.14159265358979323846
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
static TCHAR szAppName[] = TEXT("Heart");
HWND hwnd;
MSG msg;
WNDCLASS wndclass;
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = szAppName;
if (!RegisterClass(&wndclass)) {
MessageBox(NULL, TEXT("This program requires Windows NT!"), szAppName, MB_ICONERROR);
return 0;
}
hwnd = CreateWindow(szAppName, TEXT("Heart"), WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hInstance, NULL);
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
static int cxClient, cyClient;
static int cxHeart, cyHeart;
static int iAngle;
HDC hdc;
PAINTSTRUCT ps;
POINT apt[13] = {
{0, -3}, {1, -4}, {2, -4}, {3, -3},
{4, -2}, {4, -1}, {3, 0}, {2, 1},
{1, 2}, {0, 3}, {-1, 2}, {-2, 1},
{-3, 0}
};
switch (msg) {
case WM_CREATE:
cxHeart = 40;
cyHeart = 40;
SetTimer(hwnd, 1, 50, NULL);
return 0;
case WM_SIZE:
cxClient = LOWORD(lParam);
cyClient = HIWORD(lParam);
return 0;
case WM_TIMER:
iAngle += 5;
if (iAngle >= 360) {
iAngle = 0;
}
InvalidateRect(hwnd, NULL, TRUE);
return 0;
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
SelectObject(hdc, GetStockObject(NULL_BRUSH));
SelectObject(hdc, GetStockObject(BLACK_PEN));
SetViewportOrgEx(hdc, cxClient / 2, cyClient / 2, NULL);
SetWindowExtEx(hdc, 100, 100, NULL);
SetViewportExtEx(hdc, cxClient, -cyClient, NULL);
MoveToEx(hdc, cxHeart * cos((iAngle - 15) * PI / 180),
cyHeart * sin((iAngle - 15) * PI / 180), NULL);
LineTo(hdc, cxHeart * cos(iAngle * PI / 180),
cyHeart * sin(iAngle * PI / 180));
PolylineTo(hdc, apt, sizeof(apt) / sizeof(apt[0]));
LineTo(hdc, cxHeart * cos((iAngle + 15) * PI / 180),
cyHeart * sin((iAngle + 15) * PI / 180));
EndPaint(hwnd, &ps);
return 0;
case WM_DESTROY:
KillTimer(hwnd, 1);
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
```
该代码会在窗口中绘制跳动的爱心,可以通过定时器来实现爱心跳动的效果。