Creating Text

Description

AGK provides a set of functions for creating text, setting its properties and displaying it on screen. In this example we’ll focus on the basics of creating text and displaying it.

Overview

The process involved is as follows:

Creating Text

Just like other resources, text entities are handled with ID numbers. It’s possible to create them and manually assign an ID number or have an ID number automatically assigned in the creation process.

The command to create text is called CreateText. It has either 1 or 2 parameters dependant on usage. If you want an ID number assigned automatically it only takes 1 parameter - the initial text of the entity. If you want to control the ID number it takes 2 parameters - the ID number followed by the initial text of the entry. Here's an example showing the 2 methods of creating text:

CreateText ( 1, "HELLO AGK!" )
text = CreateText ( "HELLO AGK!" )

For this example the approach of assigning ID numbers manually is used.

The next stage deals with setting the size of the text. This is handled by the command SetTextSize. This function takes two parameters. The first parameter is the ID number of the text object. The second parameter is used to control the new size of the text. By default the size is set to 4. With this code the size is set to 6:

SetTextSize ( 1, 6 )

A lower size parameter will result in the text being smaller, while a larger value will make the text appear larger.

Main loop

For our main loop all we’re going to do is continually alter the colour of the text (randomly) and draw the screen. It’s handled with the following code:

do
    SetTextColor ( 1, Random ( 1, 255 ), Random ( 1, 255 ), Random ( 1, 255 ), 255 )
    Sync ( )
loop

The command SetTextColor takes four parameters:

The command Random is a utility function provided by AGK that will return a random number within the given range. The code above asks for a random value between 1 - 255 for the red, green and blue components, and finally the alpha value is always set to 255.

Full code listing

Everything is now in place. Here's the final code for our program:

backdrop = CreateSprite ( LoadImage ( "background5.jpg" ) )
SetSpriteSize ( backdrop, 100, 100 )


CreateText ( 1, "HELLO AGK!" ) SetTextSize ( 1, 6 )
do SetTextColor ( 1, Random ( 1, 255 ), Random ( 1, 255 ), Random ( 1, 255 ), 255 ) Sync ( ) loop

Conclusion

When you run the application the text on screen will continually change colour.

A lot of properties are available for text such as being able to set the string, position, spacing, alignment and much more. Please refer to the reference guide for more details.