Search code examples
text.net-2.0system.drawing

How to draw mixed-formatted text with .Net 2.0


is there a way to draw mixed-formatted text in .Net 2.0? I'm looking for something similar to

System.Drawing.Graphics.DrawString()

My problem with this method is that it allows only one format style for the whole text. But I need to draw text that has different format styles (e.g. a part of the text shall be underlined, another part bold and so on).

Thanks a lot!
Oliver


Solution

  • I'm pulling an answer right from the book WPF in Action -- You seem to have 2 options:

    • Create a custom control and define your own markup for specifying fonts. Aside from this being a lot of work, you'd also have to rely on the the notoriously inaccurate methods for measuring the width of text (so that you could figure out where to put the next word).

    • Use the RTF control. This is extremely heavy, and you'd end up spending a lot of time making it look like text instead of an edit control, and you'd have to work with RTF to get the text the way you wanted.

    So I guess the answer is the RTF control (aka. RichTextBox) if you're stuck with .NET 2.0 -- WinForms. Well, unless you want to write your own control... :-)

    The book also mentions taking various label and/or textbox controls and manually (or programatically) aligning them and setting to have different font values, etc. But I assume you want to avoid that, right?

    EDIT

    I'm leaving my above answer in-place. Here's my new answer to you:

    Look into GDI+ -- Here is a link to a tutorial at C# Corner which should introduce you to GDI+: http://www.c-sharpcorner.com/uploadfile/mahesh/gdi_plus12092005070041am/gdi_plus.aspx

    And here is a link that should show you how to use GDI+ with a Bitmap/Image: http://ondotnet.com/pub/a/dotnet/2003/05/05/gdiplus.html

    Good luck!

    Also, you may want to pick up a book on this as GDI+ is a pretty heavy topic. I did most of my learning about GDI+ via the book Pro .NET 2.0 Windows Forms and Custom Controls in C# (It's a good book in my experience.) Although since you aren't exactly interested in designing custom controls for WinForms, you may want to look for a book geared more directly toward GDI+.