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.
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.
0 is a valid handle, so you should check for
If your font file contains multiple fonts faces, you can specify which one to load by passing the font face index.
With the font loaded, you can now set it as the current font.
Now you to render text:
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.
You can change the text alignment by calling the
Horizontal alignment, which can be one of the following constants:
Vertical alignment, which can be one of the following constants:
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.
textBox() method works very similar to the
text() method, except it takes an additional parameter for the width of the box.
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.
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.