📝 基础示例:默认字体 + 自定义字体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "raylib.h"

int main(void)
{
InitWindow(800, 450, "raylib rtext example");
SetTargetFPS(60);

// 1. 默认字体(内部自带)
const char *msg1 = "Hello, raylib! 默认字体";

// 2. 加载自定义 TTF 字体
Font font = LoadFont("resources/JetBrainsMono-Regular.ttf"); // 换成你自己的 TTF
const char *msg2 = "使用自定义 TTF 字体";

while (!WindowShouldClose())
{
BeginDrawing();
ClearBackground(RAYWHITE);

// --- 默认字体 ---
DrawText(msg1, 40, 40, 20, DARKBLUE);

// --- 自定义字体 ---
DrawTextEx(font, msg2, (Vector2){40, 100}, 32, 2, MAROON);

// --- 文本测量 + 居中 ---
const char *msg3 = "居中显示的文本";
int fontSize = 30;
int spacing = 2;
Vector2 size = MeasureTextEx(font, msg3, fontSize, spacing);

Vector2 pos = {
(GetScreenWidth() - size.x) / 2.0f,
(GetScreenHeight() - size.y) / 2.0f
};

DrawTextEx(font, msg3, pos, fontSize, spacing, DARKGREEN);

// --- 文本对齐示意 ---
DrawText("左上角", 10, GetScreenHeight() - 30, 20, GRAY);
DrawText("右上角", GetScreenWidth() - MeasureText("右上角", 20) - 10, 10, 20, GRAY);

EndDrawing();
}

// 卸载自定义字体
UnloadFont(font);

CloseWindow();
return 0;
}

🔧 这里用到的 rtext 关键 API

  • DrawText() 使用默认字体绘制文本(简单粗暴,够用)
  • LoadFont() / UnloadFont() 加载/卸载自定义 TTF 字体
  • DrawTextEx(Font font, Vector2 pos, float fontSize, float spacing, Color tint) 更灵活的文本绘制(支持任意字体、字号、字间距)
  • MeasureTextEx(Font font, const char *text, float fontSize, float spacing) 测量文本像素尺寸,用来做居中、对齐