ch03.md 1.9 KB

Chapter 3. Rendering Text

The pixels library can do slightly more than just putPixel: it also offers a minimal drawText proc, to put letters and words on the screen. Its declaration looks like this:

  proc drawText(x, y: int; text: string; size: int; color: Color)

We pass the following parameters to it: x and y

The coordinates of a bottom-left corner of the text we want to draw

text

The text we want to render. It is of type string. We will look at strings in
more depth in the next chapter, for now it is enough to know that string
is a builtin type that is roughly a sequence of char, and a string literal can
be written in double quotes, for example "like this".

size

This is a height of the text in pixels.

color

Similarly to the putPixel proc, we can define the color of the text we’re
drawing.

The simplest way to call this proc is like this: drawText 30, 40, "Welcome to Nim!", 10, Yellow Notice that we didn’t use the parentheses after the name of the function to

                                                                            25

enclose the list of arguments. This is equivalent to drawText(10, 10, "Welcome to Nim!", Yellow), either style can be used. For the next more interesting example we need the dollar operator $ which can turn many types into its string representation, and the concatenation operator & which combines (“concatenates”) two strings into one: $12 == "12" # convert an integer into a string "abc" & "def" == "abcdef" # concatenate two strings into one The following example produces 3 lines of text: for i in 1..3: let texttodraw = "welcome to nim for the " & $i & "th time!" 1 drawtext 10, i*10, texttodraw, 8, Yellow 2 1 Creates a string (concatenated from three separate strings) and assigns it

to the local variable textToDraw.

2 Renders the text at position (10, i*10) where i is in one of the numbers in the 1..3 range, for each loop iteration.