January 1998

Drawing text 101

by Kent Reisdorph

Let's examine the basics of displaying text onscreen. The TCanvas class has a TextOut() method that you can use to display text on a canvas. The following code uses TextOut() to display a line of text on a form starting at position 20, 20 (20 pixels from the left of the form and 20 pixels from the top):

Canvas->TextOut(20, 20, "C++Builder Rules!");
The text is drawn on the form using the form's Font property settings. Testing this method is easy: Simply place a button on a form and enter our sample line of code in the button's OnClick handler. When you run the program, you'll notice that the text has a white background--this background is the default for text displayed with TextOut(), but it isn't very appealing. In order to let the background color show through, you must make the text transparent by setting the brush style to bsClear. To do so, add one line to the previous code:
Canvas->Brush->Style = bsClear;
Canvas->TextOut(20, 20, "C++Builder Rules!");
You could accomplish the same result by setting the brush color to the form's background color, but setting the style to bsClear is preferable because you don't have to worry about what's on the form beneath the text. Figure A shows a program that displays text using TextOut(). The program displayed the first line before setting the brush style to clear and the second line after setting the brush style to clear.

Figure A: Our sample program displays text using TextOut().
[ Figure A ]

The TextOut() method of TCanvas simply calls the Windows API function of the same name. There's another text function in the Windows API that we should mention: DrawText(). It provides a more flexible method of displaying text on a canvas. DrawText() lets you center text horizontally and vertically, right-justify text, left-justify text, truncate too-long text with an ellipsis (...), and perform other specialized functions.

For whatever reason, the TCanvas class doesn't have a DrawText() method. So to use DrawText(),you'll have to call on the API. A typical DrawText() call would look something like this:

TRect r = Rect(20, 20, 120, 40);
DrawText(Canvas->Handle, "DrawText in action",
  -1, (RECT*)&r, DT_SINGLELINE);
While this code might seem like a lot more work, keep in mind that sometimes DrawText() is the only way to display text in exactly the way you want. We won't go into detail about DrawText() here; see the Win32 API online Help for more information. This is one function that should definitely be in your arsenal if you're going to write your own components.