TextRenderer is slow, DrawString is wrong

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.

Creative Commons License
This work, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 License.
This entry was posted in .net, C#, Programming and tagged , , , , , , , , . Bookmark the permalink.

2 Responses to TextRenderer is slow, DrawString is wrong

  1. Pingback: » Next version: Globalization + Save and Print Colour Images ASCII Generator dotNET: Image to text program

  2. nobuyuki says:

    Hello!!!!! I know this post is years old, but this might be useful to people who stumble upon your page in the future. DrawString() has a method which takes a StringFormat as a parameter. The secret to removing the padding in DrawString is to specify a StringFormat which removes the padding. StringFormat.GenericTypographic does just that.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>