After struggling with WinAPI code and hacks in .NET 1.0 I was really looking forward to the TextRenderer class when I first heard about it. But as it turns out, not only is TextRenderer horrible at measuring character size it is also monumentally slow at rendering text.
All I needed to do was to draw a series of characters onto an image, each one having a different Color value. Easy right? Straightforward code, plug it in to the Ascgen and… wait… we get the output required. After a quick profile of the application, it was clear that the problem was with the external function and there was nothing that could be done to speed things up to an acceptable level.
Before digging into api functions, I decided to look back to the older method of drawing strings: Graphics.DrawString.
The code is less straightforward, but, despite having to create a new SolidBrush object for every Color, it works quickly. An image that took around 10 seconds with TextRenderer takes milliseconds with DrawString. The only obvious problem was that DrawString shifted the text right a fraction, but a quick google leads to a solution: using StringFormat.GenericTypographic in the call.
Now, the next obvious step was to use DrawString to improve the speed of drawing text all in one Color, and that’s where it all goes wrong: DrawString adds extra space between characters, and there doesn’t seem to be a way to stop it.
Applying the same code as before and printing each character separately (after first having to split it into a string array) gives the text spaced correctly. However it’s actually marginally slower then calling TextRenderer once on the whole string, and far more complicated.
Ideally I’d like to put the two together, so I need to either find a way to speed up TextRenderer or a way to fix the spacing in DrawString.
This work, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 License.