C++GDI绘制直角坐标系,坐标原点在窗口中心,并绘制刻度,在第一象限绘制矩形并标注字母
时间: 2024-04-07 16:33:45 浏览: 19
您好!以下是使用C++和GDI绘制直角坐标系、刻度和标注字母的示例代码:
```cpp
#include <windows.h>
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// 创建窗口
const wchar_t CLASS_NAME[] = L"Sample Window Class";
WNDCLASS wc = {};
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
RegisterClass(&wc);
HWND hwnd = CreateWindowEx(
0, // Optional window styles.
CLASS_NAME, // Window class
L"Direct2D Sample", // Window text
WS_OVERLAPPEDWINDOW, // Window style
// Size and position
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, // Parent window
NULL, // Menu
hInstance, // Instance handle
NULL // Additional application data
);
if (hwnd == NULL)
{
return 0;
}
ShowWindow(hwnd, nCmdShow);
// 消息循环
MSG msg = {};
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
// 获取窗口尺寸
RECT rect;
GetClientRect(hwnd, &rect);
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
// 设置坐标原点在窗口中心
SetViewportOrgEx(hdc, width / 2, height / 2, NULL);
// 绘制直角坐标系
MoveToEx(hdc, -width / 2, 0, NULL);
LineTo(hdc, width / 2, 0);
MoveToEx(hdc, 0, -height / 2, NULL);
LineTo(hdc, 0, height / 2);
// 绘制刻度
for (int i = -width / 2; i <= width / 2; i += 50)
{
MoveToEx(hdc, i, -5, NULL);
LineTo(hdc, i, 5);
}
for (int i = -height / 2; i <= height / 2; i += 50)
{
MoveToEx(hdc, -5, i, NULL);
LineTo(hdc, 5, i);
}
// 在第一象限绘制矩形并标注字母
RECT rect1 = { 50, -50, 150, -150 };
Rectangle(hdc, rect1.left, rect1.top, rect1.right, rect1.bottom);
DrawText(hdc, L"A", -1, &rect1, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
EndPaint(hwnd, &ps);
}
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
}
```
此代码创建了一个窗口,并使用GDI在窗口中心绘制了一个直角坐标系、刻度和一个在第一象限的矩形,并标注了字母"A"。
请注意,这只是一个简单的示例代码,您可能需要根据您的实际需求进行修改和扩展。希望对您有帮助!如果还有其他问题,请随时提问。