Text & Fonts¶
Rendering text is a fundamental aspect of many graphics applications, from displaying user interface elements to showing in-game information. However, implementing custom text rendering can be complex and time-consuming, especially when dealing with various font styles and sizes. PHP-GLFW's Vector Graphics API allows you the use of TrueType Font (TTF) files.
Loading Fonts¶
First you need to load a font file. You can do this by calling the createFont()
method on the VectorGraphics
context object.
- The first parameter is the name of the font, which you can use to reference the font later.
- The second parameter is the path to the font file.
The returned integer is the font handle. The function will return -1
if the font could not be loaded.
Note
0
is a valid handle, so you should check for -1
specifically.
If your font file contains multiple fonts faces, you can specify which one to load by passing the font face index.
Rendering Text¶
With the font loaded, you can now set it as the current font.
Now you to render text:
$vg->beginPath();
$vg->fontSize(20);
$vg->fillColor(VGColor::green());
// text(x, y, string)
$vg->text(50, 50, 'Hello World!');
You do not have to set the font size every time you render text. The Vector Graphics API behaves like a state machine, so the font size will be remembered until you change it again.
Text Alignment¶
You can change the text alignment by calling the textAlign()
method.
-
Horizontal alignment, which can be one of the following constants:
VGAlign::LEFT
VGAlign::CENTER
VGAlign::RIGHT
-
Vertical alignment, which can be one of the following constants:
VGAlign::TOP
VGAlign::MIDDLE
VGAlign::BOTTOM
VGAlign::BASELINE
Text Boxes¶
You can render text inside a box by calling the textBox()
method. This method will automatically wrap the text to fit inside of a given width.
The textBox()
method works very similar to the text()
method, except it takes an additional parameter for the width of the box.
Text Metrics¶
When working with text, you will pretty quickly end up in a situation where you need to know the size of the text you are rendering.
X Advance¶
For exmaple, lets say we want to render a sentence where each word is a different color. The text
function will actually return the x position + width of the text it rendered. So we can use this to render the next word at the correct position.