Using Graphics.TextRenderingHint with TextRenderer.DrawText to get anti-aliased text in ToolStripItem

468 Views Asked by At

I need to enhance one legacy WinForms app to support the inheritance of the TextRenderingHint setting in the app forms.

For simplicity, let's suppose that we have a main form with the TextRenderingHint property of the System.Drawing.Text.TextRenderingHint type. This property specifies the text quality in the main form and must be inherited in dialog forms called from this main form. The text in the main form is drawn using Graphics.DrawString method, and there is no problem to support various settings of the main form's TextRenderingHint property (in fact, it is simply assigned to Graphics.TextRenderingHint before drawing text with Graphics.DrawString).

The problem is that the interface of one of the dialogs is based on the WinForms ToolStrip component and I need to redefine text drawing in its items to support the TextRenderingHint setting of the main form.

After searching the Internet and analyzing the source code of the ToolStripRenderer class in a reflector app, I came to the conclusion that the best way to implement what I need is to use a custom ToolStrip renderer with the redefined OnRenderItemText method.

I found the following code in the default implementation of the OnRenderItemText method in the ToolStripRenderer class (see the full code at the bottom of my question):

graphics2.TextRenderingHint = TextRenderingHint.AntiAlias
TextRenderer.DrawText(graphics2, text, textFont, New Rectangle(Point.Empty, size), color, textFormat)

, which gave me an idea that I could try to solve my problem with this simple implementation of OnRenderItemText in a class derived from ToolStripRenderer:

Protected Overrides Sub OnRenderItemText(e As ToolStripItemTextRenderEventArgs)
    e.Graphics.TextRenderingHint = _MainFormTextRenderingHint
    MyBase.OnRenderItemText(e)
End Sub

My idea is based on the fact that if we do not use vertical text in ToolStrip items (we don't), the basic OnRenderItemText method "just" calls TextRenderer.DrawText and theoretically my idea could work. Unfortunately, in practice this works only for the TextRenderingHint.ClearTypeGridFit option - at least, on my dev pc.

The only viable idea I see now is complete rewriting of OnRenderItemText and using Graphics.DrawString inside. Am I right? Are there other solutions to my problem?

UPDATE #1. I encountered a problem trying to reimplement OnRenderItemText based on Graphics.DrawString. It seems, it's impossible to convert text format flags passed to TextRenderer.DrawText (the TextFormatFlags enumeration) to the StringFormatClass parameter Graphics.DrawString expects...

UPDATE #2. The default implementation of the OnRenderItemText method in the ToolStripRenderer class is the following:

enter image description here

0

There are 0 best solutions below