在raylib中使用DrawRectangleLines()时如何设置更粗的线条?
解决raylib中DrawRectangleLines无法修改线条粗细的问题
raylib的DrawRectangleLines()确实仅支持1像素粗细的矩形边框,官方没有提供直接调整线条宽度的参数。这里提供两种无需创建纹理的实用解决方案:
方法1:叠加绘制多层偏移矩形线
通过循环绘制多次偏移后的矩形线,叠加出粗边框效果。该方法适用于任何背景场景,不受颜色限制。
封装函数示例:
#include "raylib.h" // 自定义粗边框矩形绘制函数 void DrawRectangleLinesThick(Rectangle rec, int thickness, Color color) { for (int i = 0; i < thickness; i++) { // 每次循环向内偏移i像素,同时缩小宽高以保持整体尺寸一致 DrawRectangleLines( (int)rec.x + i, (int)rec.y + i, (int)rec.width - 2 * i, (int)rec.height - 2 * i, color ); } } // 使用示例 int main() { InitWindow(800, 450, "Thick Rectangle Border"); SetTargetFPS(60); Rectangle rect = { 100, 100, 200, 150 }; int borderThickness = 5; while (!WindowShouldClose()) { BeginDrawing(); ClearBackground(RAYWHITE); // 调用自定义函数绘制粗边框 DrawRectangleLinesThick(rect, borderThickness, RED); EndDrawing(); } CloseWindow(); return 0; }
方法2:填充矩形挖空法
通过绘制外层填充矩形,再用背景色填充内层区域,间接形成粗边框。该方法性能更优,但仅适用于纯色背景的场景。
封装函数示例:
#include "raylib.h" void DrawRectangleBorderFill(Rectangle rec, int thickness, Color borderColor, Color bgColor) { // 绘制外层填充矩形作为边框基础 DrawRectangleRec(rec, borderColor); // 绘制内层填充矩形,覆盖中间区域,留下边框 Rectangle innerRec = { rec.x + thickness, rec.y + thickness, rec.width - 2 * thickness, rec.height - 2 * thickness }; DrawRectangleRec(innerRec, bgColor); } // 使用示例 int main() { InitWindow(800, 450, "Thick Border via Fill"); SetTargetFPS(60); Rectangle rect = { 100, 100, 200, 150 }; int borderThickness = 5; while (!WindowShouldClose()) { BeginDrawing(); ClearBackground(RAYWHITE); // 传入背景色(此处为窗口背景色RAYWHITE) DrawRectangleBorderFill(rect, borderThickness, BLUE, RAYWHITE); EndDrawing(); } CloseWindow(); return 0; }
两种方法都无需额外创建纹理,可根据你的场景需求选择使用。
内容的提问来源于stack exchange,提问作者SimpfeyIsDumb
相关产品推荐
相关产品推荐

