掌握矩形绘制——最常用的 UI 图元,学习填充、描边及 xge_rect_t 的使用。
矩形是 UI 和游戏 HUD 中最常见的图元。XGE 提供填充(Fill)和描边(Stroke)两种绘制方式,均以 xge_rect_t 定义区域。
| 函数 | 说明 |
|---|---|
void xgeShapeRectFill(xge_rect_t tRect, uint32_t iColor) | 填充矩形 |
void xgeShapeRectFillPx(xge_rect_t tRect, uint32_t iColor) | 填充矩形(像素坐标) |
void xgeShapeRectStroke(xge_rect_t tRect, float fWidth, uint32_t iColor) | 描边矩形 |
void xgeShapeRectStrokePx(xge_rect_t tRect, float fWidth, uint32_t iColor) | 描边矩形(像素坐标) |
gcc -O2 -I. -o ch22.exe ch22_main.c build\xge.lib -lm -lws2_32 -liphlpapi -lgdi32 -luser32 -lshell32 -lopengl32 -lole32 -lwinmm -lavrt
.\ch22.exe
xge_rect_t r = { 100, 100, 300, 200 }; // x, y, w, h
xgeShapeRectFill(r, 0x4FD8C2FF);
// 半透明叠加
xge_rect_t r2 = { 200, 150, 300, 200 };
xgeShapeRectFill(r2, 0xFFB45480); // Alpha=0x80 (50%)// 2px 描边
xge_rect_t box = { 150, 250, 500, 100 };
xgeShapeRectStroke(box, 2.0f, 0xFF6B5EFF);
// 填充 + 描边组合
xgeShapeRectFill(box, 0x1A2A30FF);
xgeShapeRectStroke(box, 1.5f, 0x6DB3F2FF);// 绘制 40px 网格
for (float x = 0; x < 800; x += 40)
xgeShapeLine(x, 0, x, 600, 0.5f, 0x1A2A3040);
for (float y = 0; y < 600; y += 40)
xgeShapeLine(0, y, 800, y, 0.5f, 0x1A2A3040);
// 高亮选中单元格
xge_rect_t cell = { 120, 80, 40, 40 };
xgeShapeRectFill(cell, 0x4FD8C230);
xgeShapeRectStroke(cell, 1.0f, 0x4FD8C2FF);将以下代码保存为 ch22_main.c,编译后运行即可看到矩形的填充与描边效果:
#include "xge.h"
static int onFrame(void* pUser) {
(void)pUser;
xgeClear(0x081114FF);
// 填充矩形
xgeShapeRectFill(100, 100, 250, 150, 0x4FD8C2FF);
// 描边矩形(线宽 3)
xgeShapeRectStroke((xge_rect_t){450, 100, 250, 150}, 0xFFB454FF, 3.0f)
// 半透明填充 + 描边组合
xgeShapeRectFill(200, 350, 400, 180, 0x6DB3F240);
xgeShapeRectStroke((xge_rect_t){200, 350, 400, 180}, 0x6DB3F2FF, 2.0f)
return XGE_OK;
}
int main(void) {
xge_desc_t d = {0};
d.iWidth = 800;
d.iHeight = 600;
d.sTitle = "ch22 - Rectangles";
d.iFlags = XGE_INIT_VSYNC;
xgeInit(&d);
xgeRun(onFrame, NULL);
xgeUnit();
return 0;
}xgeShapeRectFill(x, y, w, h, color) 绘制实心矩形,(x,y) 为左上角。xgeShapeRectStroke((xge_rect_t){x, y, w, h}, width, color) 绘制矩形边框,width 为线宽。40(Alpha=64)表示约 25% 不透明度。