用c语言写一个红色的心
时间: 2023-06-10 21:06:27 浏览: 40
很抱歉,C语言并不适合直接绘制图形,需要调用操作系统提供的图形库或者使用第三方库来完成。以下是使用Windows GDI绘制红色心形的示例代码:
```c
#include <windows.h>
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, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hInstance, NULL);
ShowWindow(hwnd, iCmdShow);
UpdateWindow(hwnd);
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
static int cxClient, cyClient;
HDC hdc;
PAINTSTRUCT ps;
HPEN hPen;
HBRUSH hBrush;
switch (message)
{
case WM_SIZE:
cxClient = LOWORD(lParam);
cyClient = HIWORD(lParam);
return 0;
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
hPen = CreatePen(PS_SOLID, 2, RGB(255, 0, 0));
hBrush = CreateSolidBrush(RGB(255, 0, 0));
SelectObject(hdc, hPen);
SelectObject(hdc, hBrush);
int x = cxClient / 2;
int y = cyClient / 2 - 20;
int r = 50;
// 绘制心形
MoveToEx(hdc, x, y, NULL);
for (double theta = 0; theta < 2 * 3.14; theta += 0.01)
{
double x1 = r * (16 * pow(sin(theta), 3));
double y1 = -r * (13 * cos(theta) - 5 * cos(2 * theta) - 2 * cos(3 * theta) - cos(4 * theta));
LineTo(hdc, x + x1, y + y1);
}
DeleteObject(hPen);
DeleteObject(hBrush);
EndPaint(hwnd, &ps);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
```
编译链接后运行,即可看到一个红色的心形窗口。