GDI+ 中绘制圆角矩形:解决 "Gdiplus::Graphics" 类没有 "DrawRoundRect" 方法的问题
GDI+ 库中的 'Graphics' 类确实没有 'DrawRoundRect' 方法。为了实现绘制圆角矩形,我们可以使用 GDI 函数来进行绘制。以下是修改后的代码:
#include <windows.h>
#include <gdiplus.h>
using namespace Gdiplus;
void DrawCustomControl(HWND hwnd, COLORREF borderColor = RGB(0, 0, 0), COLORREF buttonColor = RGB(255, 255, 255)) {
HDC hdc = GetDC(hwnd);
RECT rect;
GetClientRect(hwnd, &rect);
// 绘制背景色
HBRUSH hBrush = CreateSolidBrush(buttonColor);
FillRect(hdc, &rect, hBrush);
DeleteObject(hBrush);
// 绘制圆角矩形边框
HPEN hPen = CreatePen(PS_SOLID, 2, borderColor);
SelectObject(hdc, hPen);
RoundRect(hdc, rect.left, rect.top, rect.right, rect.bottom, 10, 10);
DeleteObject(hPen);
ReleaseDC(hwnd, hdc);
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
case WM_PAINT: {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
// 调用自定义绘制函数
DrawCustomControl(hwnd, RGB(255, 0, 0), RGB(0, 0, 255));
EndPaint(hwnd, &ps);
return 0;
}
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
// 初始化 GDI+
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
// 创建窗口
WNDCLASSEX wc = {0};
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszClassName = L"WindowClass";
RegisterClassEx(&wc);
HWND hwnd = CreateWindowEx(0, L"WindowClass", L"Window", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 500, 300,
NULL, NULL, hInstance, NULL);
ShowWindow(hwnd, nCmdShow);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// 释放 GDI+
GdiplusShutdown(gdiplusToken);
return (int)msg.wParam;
}
在示例代码中,我们使用了 GDI 函数 'RoundRect' 来绘制圆角矩形边框。在 'DrawCustomControl' 函数中,我们创建了一个 'HPEN' 对象,设置边框颜色和宽度,然后将其选入设备上下文,并调用 'RoundRect' 函数绘制圆角矩形。
再次对之前的错误表示歉意,希望新的示例代码能够满足你的需求。如果还有任何问题,请随时提问。
原文地址: https://www.cveoy.top/t/topic/Tuc 著作权归作者所有。请勿转载和采集!