c语言的爱心代码会动的
时间: 2023-12-25 17:28:50 浏览: 110
以下是使用C语言实现动态爱心的代码,它使用了Windows API来创建窗口和绘制图形:
```c
#include <windows.h>
#include <math.h>
#define PI 3.14159265358979323846
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR szCmdLine, int iCmdShow)
{
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,
400, 400,
NULL, NULL, hInstance, NULL);
ShowWindow(hwnd, iCmdShow);
UpdateWindow(hwnd);
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
void DrawHeart(HDC hdc, int x, int y, int size)
{
double angle, radian;
int px, py;
int i;
for (i = 0; i < 360; i++)
{
angle = (double)i;
radian = angle * PI / 180.0;
px = (int)(16.0 * pow(sin(radian), 3) * size + 0.5);
py = (int)(-(13.0 * cos(radian) - 5.0 * cos(2 * radian) - 2.0 * cos(3 * radian) - cos(4 * radian)) * size + 0.5);
SetPixel(hdc, x + px, y + py, RGB(255, 0, 0));
}
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
static int cxClient, cyClient;
HDC hdc;
PAINTSTRUCT ps;
switch (message)
{
case WM_SIZE:
cxClient = LOWORD(lParam);
cyClient = HIWORD(lParam);
return 0;
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
DrawHeart(hdc, cxClient / 2, cyClient / 2, min(cxClient, cyClient) / 30);
EndPaint(hwnd, &ps);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
```
运行后会弹出一个窗口,里面会动态地显示一个红色的爱心。
阅读全文