Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way to draw formatted text in the Win32 API?

I am implementing a text editor in C++ just using the vanilla Win32 API and I'm trying to find the best way to implement syntax highlighting. I know that there are existing controls out there like scintilla, but I'm doing this for fun so I want to do most of the work myself. I also want it to be fast and lightweight.

From what I've learned so far, it looks like the most low level option for drawing text in GDI is the TextOut function. However, if I need to keep changing the font color then that means I will need to make many calls to TextOut in order to draw one body of text with mixed formatting. Is this inefficient? When syntax highlighting and rich text controls are implemented, would they be likely to use TextOut behind the scenes or is there some other way? Is every other method of drawing text in GDI just a higher level wrapper around TextOut?

like image 671
Graeme Hill Avatar asked Apr 05 '11 04:04

Graeme Hill


1 Answers

Both DrawText and TextOut are wrappers for ExtTextOut, so ExtTextOut is the low-level API. In my experience, ExtTextOut is pretty fast, so I doubt you'll see any performance issues with ExtTextOut itself. However, creating/selecting fonts can be a source of performance issues, so if you are switching back and forth between fonts, you can realize significant performance gains by caching and reusing fonts (HFONT) rather than CreateFont / SelectObject / DeleteObject each time. Basically, the first time you call SelectObject after creating a new font, Windows will perform a font matching process to find the best physical font for the logical font that you have requested. This is a fairly complex process, so you want to minimize the number of times that occurs in situations where performance is important.

I developed a rich edit control many years ago that was essentially a mini version of Microsoft Word. I used ExtTextOut as the main workhorse for all text output. The control would maintain a font cache of the most recently used fonts (default cache size was 10 fonts). It supported WYSIWYG layout, so it was actually doing all layout using a printer DC and fonts, then would render a screen compatible version using a screen DC and similar fonts, so there was a lot of extra work going on that likely is not applicable to your situation. Even so, performance was excellent running on typical hardware of the day (e.g., 266 mhz Pentium).

like image 134
cbranch Avatar answered Sep 28 '22 12:09

cbranch