C++GDI绘制直角坐标系,坐标原点在窗口中心,并绘制刻度
时间: 2024-04-07 21:33:24 浏览: 62
您可以使用C++的GDI库来绘制直角坐标系,并将坐标原点放置在窗口的中心。以下是一个简单的示例代码:
```cpp
#include <Windows.h>
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, 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 = WndProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
RegisterClass(&wc);
HWND hwnd = CreateWindowEx(
0,
CLASS_NAME,
L"Sample Window",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL,
NULL,
hInstance,
NULL
);
if (hwnd == NULL)
{
return 0;
}
ShowWindow(hwnd, nCmdShow);
// 消息循环
MSG msg = {};
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
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;
// 将坐标原点移动到窗口中心
int originX = width / 2;
int originY = height / 2;
// 绘制直角坐标系
SelectObject(hdc, GetStockObject(DC_PEN));
SetDCPenColor(hdc, RGB(0, 0, 0));
MoveToEx(hdc, 0, originY, NULL);
LineTo(hdc, width, originY);
MoveToEx(hdc, originX, 0, NULL);
LineTo(hdc, originX, height);
// 绘制刻度
SelectObject(hdc, GetStockObject(DC_BRUSH));
SetDCBrushColor(hdc, RGB(0, 0, 0));
int scaleLength = 10; // 刻度的长度
int scaleInterval = 50; // 刻度之间的间隔
// 绘制X轴刻度
for (int x = originX + scaleInterval; x < width; x += scaleInterval)
{
Rectangle(hdc, x, originY - scaleLength / 2, x + 1, originY + scaleLength / 2);
}
for (int x = originX - scaleInterval; x > 0; x -= scaleInterval)
{
Rectangle(hdc, x, originY - scaleLength / 2, x + 1, originY + scaleLength / 2);
}
// 绘制Y轴刻度
for (int y = originY + scaleInterval; y < height; y += scaleInterval)
{
Rectangle(hdc, originX - scaleLength / 2, y, originX + scaleLength / 2, y + 1);
}
for (int y = originY - scaleInterval; y > 0; y -= scaleInterval)
{
Rectangle(hdc, originX - scaleLength / 2, y, originX + scaleLength / 2, y + 1);
}
EndPaint(hwnd, &ps);
break;
}
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
```
这段代码会创建一个简单的窗口,并在窗口的`WM_PAINT`消息处理函数中绘制直角坐标系和刻度。您可以将该代码保存为一个.cpp文件,然后使用Visual Studio等编译器进行编译运行。窗口会显示一个带有直角坐标系和刻度的画布。
请注意,这只是一个简单的示例,绘制的直角坐标系和刻度可能不是非常准确和完整,您可以根据自己的需求进行修改和扩展。
阅读全文