Windows GDI 提供豐富的矩形操作 API,核心結構 RECT(左、上、右、下)配合繪圖、幾何計算函數,構成界面繪製、碰撞檢測、區域裁剪的基礎。本文系統整理 RECT 相關 API。
typedef struct tagRECT {
LONG left; // 最小 x
LONG top; // 最小 y
LONG right; // 最大 x
LONG bottom; // 最大 y
} RECT, *PRECT, *LPRECT;
坐標為邏輯坐標,寬度 = right - left,高度 = bottom - top。
| 函數 | 用途 | 特點 |
|---|---|---|
FillRect(hdc, &rect, hbr) | 用畫刷填充矩形 | 無需先選入畫刷,邊界不繪製 |
FrameRect(hdc, &rect, hbr) | 用畫刷繪製矩形邊框 | 邊框寬 1 邏輯單位,支持花紋畫刷 |
InvertRect(hdc, &rect) | 顏色反轉(黑↔白、綠↔洋紅) | 像素級 XOR,常用於選中高亮 |
| 函數 | 原型 | 說明 |
|---|---|---|
| SetRect | BOOL SetRect(LPRECT lprc, int xLeft, int yTop, int xRight, int yBottom) | 一次性設置四個座標 |
| OffsetRect | BOOL OffsetRect(LPRECT lprc, int dx, int dy) | 整體平移(左/右/上/下同增減) |
| InflateRect | BOOL InflateRect(LPRECT lprc, int dx, int dy) | 擴大/縮小:左-=dx, 右+=dx, 上-=dy, 下+=dy |
| SetRectEmpty | BOOL SetRectEmpty(LPRECT lprc) | 置零(left=top=right=bottom=0) |
| CopyRect | BOOL CopyRect(LPRECT lprcDst, CONST RECT* lprcSrc) | 結構體拷貝 |
| IntersectRect | BOOL IntersectRect(LPRECT lprcDst, CONST RECT* lprc1, CONST RECT* lprc2) | 求交集(無交集返回 FALSE,Dst 置空) |
| UnionRect | BOOL UnionRect(LPRECT lprcDst, CONST RECT* lprc1, CONST RECT* lprc2) | 求並集(外接矩形) |
| IsRectEmpty | BOOL IsRectEmpty(CONST RECT* lprc) | 判斷寬或高 ≤ 0 |
| PtInRect | BOOL PtInRect(CONST RECT* lprc, POINT pt) | 點是否在矩形內(含左上邊,不含右下邊) |
RECT rc = {10, 10, 100, 80};
HBRUSH hbr = CreateSolidBrush(RGB(0, 128, 255));
FillRect(hdc, &rc, hbr); // 填充藍色矩形
FrameRect(hdc, &rc, GetStockObject(BLACK_BRUSH)); // 黑框
InflateRect(&rc, 5, 5); // 向外擴張 5 像素
OffsetRect(&rc, 20, 0); // 右移 20
POINT pt = {50, 50};
if (PtInRect(&rc, pt)) { /* 命中 */ }
矩形是區域的基本構建塊。CreateRectRgn/CreateRectRgnIndirect 創建矩形區域,CombineRgn(RGN_OR/AND/XOR/DIFF)進行布爾運算,構建任意多邊形、橢圓組合區域,用於不規則窗口、裁剪路徑、命中測試。
RECT 坐標包含關係:left ≤ x < right,top ≤ y < bottom(右下邊不屬於矩形內部)。BOOL,失敗返回 0,調用前務必檢查指針有效性。GetDpiForWindow/SetProcessDpiAwareness 處理。熟練掌握 RECT API,是 Windows 桌面開發、遊戲碰撞檢測、自定義控件繪製的基本功。