[racket] More than one color with draw-text?

From: Neil Toronto (neil.toronto at gmail.com)
Date: Mon Dec 12 11:22:01 EST 2011

On 12/12/2011 08:53 AM, Will Robinson wrote:
> Hello,
> I'm trying to do a simple Roguelike game as an exercise in learning the
> language, particularly racket/gui.  I'm using draw-text to place
> characters on the screen.  Ideally, I'd just call this once and put up
> huge string full of newlines to represent a block of text.  My problem
> is that I want to have control of the color of each character in this
> block of text.  It seems to me that the color controls for draw-text are
> applied to the entire block at once.  Should I just call draw-text for
> each character in the block, individually assigning color?  That seems
> to be very slow computationally, not to mention more work on the poor coder.

Take a look at the `slideshow/pict' module, specifically these functions:

  * `text': creates a pict that draws text (see `tt' in `slideshow' for
    how to make monospace text, or just use `tt' itself)
  * `hbl-append': horizontally appends picts, matching up their baselines
  * `draw-pict': draws a pict on a dc<%> at a certain x,y
  * `colorize': returns a pict with a different color

You might consider making a string parser that outputs `hbl-append'-ed 
picts and recognizes two-character escapes like "^3" as commands to 
change the color for the remainder of the string.

(You could even use `para' (from `slideshow') instead of `hbl-append', 
which will decode and wrap text. That's a bit hacky, though, as it might 
depend on slideshow parameters in ways you don't expect.)

By the way, compared to actually drawing the text, any overhead from 
parsing or constructing picts is computationally cheap.

Neil T

Posted on the users mailing list.