C++ Winapi - 如何绘制填充形状矩形并设置边框粗细?

C++ Winapi - How to draw a fill shape rectangle and set the border thickness?

我正在尝试绘制一个带边框的矩形。

RECT rect;
GetClientRect(hwnd, &rect);
            
FillRect((HDC)wParam, &rect, CreateSolidBrush(RGB(0,0,0)));      //black fill
FrameRect((HDC)wParam, &rect, CreateSolidBrush(RGB(255,0,0)));   //red border

上面的代码有效,但实际上我不确定这是否是正确的方法。

反正我想设置边框的粗细。但我很难弄清楚如何。任何人都可以指出正确的方向或更好地举一个有效的例子吗?

FrameRect 文件说

The width and height of the border are always one logical unit.

因此,一种选择是更改逻辑单元和物理单元之间的映射。如果不想打乱后续的绘图操作,则必须保存旧映射并在绘制矩形和框架后恢复它。当映射更改时,矩形尺寸将需要更改。真是一团糟!

更好更简单的选择是停止使用 FrameRect。只需使用 FillRect 和边框画笔,然后 DeflateRect 获得代表内部的矩形,然后 FillRect 使用填充画笔绘制该矩形。 DeflateRect 的参数将决定边框粗细。

这不适用于像 FrameRect 那样创建空心边框,但对于填充矩形上的边框,这是一个优雅的解决方案。

如果 GDI+ 被允许,那么我会这样做

int width = 100;        //set the width.
int height = 100;       //set the height.
int borderSize = 5;     //set border size.
        
HDC hdc = GetDC(hwnd); //don't forget to release later when done. 
Graphics g(hdc);        
        
SolidBrush brush((Color(255, 241, 103, 210)));  //Set the fill color.
Pen pen(Color(255,255, 0, 0), borderSize);      //Set the border color and border size.

width = width-borderSize;                       //deduct the border size to width to get the same point we wanted, for border only.
height = height-borderSize;                     //deduct the border size to height to get the same point we wanted, for border only

g.DrawRectangle(&pen, (borderSize / 2), (borderSize / 2), width, height); //draw the border
g.FillRectangle(&brush, borderSize, borderSize, width-borderSize, height - borderSize); //draw the fill shape, and again deduct the border size to the width and height to get the same point we wanted.
        
DeleteObject(&brush);   //always delete object 
DeleteObject(&pen);     //always delete object
ReleaseDC(hwnd, hdc);   //always release hdc

有点玄乎,具体解释见评论