Click here to Skip to main content
15,892,298 members
Articles / Programming Languages / C#
Article

Using MeasureCharacterRanges to Draw Text

Rate me:
Please Sign up or sign in to vote.
3.35/5 (10 votes)
10 Jun 20041 min read 96.8K   1.7K   27   5
How to use MeasureCharacterRanges to calculate the bounding rectangles of charaters in a string, to allow characters to be placed along curves.

Sample Image - TryApp.gif

Introduction

This article will demonstrate the use of MeasureCharacterRanges to draw a string a character at a time. Not very exciting, I hear you cry. Bear with me.

Background

I wrote this short article after seeing a question posted on a newsgroup about being able to draw text along a curve. While drawing a character at a time is easy, I wanted to make sure the character spacing was maintained.

The code

Just set up some text to work with:

C#
string measureString = "This is a test string.";
int    numChars         = measureString.Length;

Initialize the character ranges array, this is used to delimit the blocks of characters in the string, in this example, each character is a 'range'.

C#
//
// Set up the characted ranger array.

Now, initialize the StringFormatFlags, I'm using the NoClips flag to ensure that the character is not clipped when drawing.

C#
//
// Set up the string format
StringFormat stringFormat = new StringFormat();
stringFormat.FormatFlags = StringFormatFlags.NoClip;
stringFormat.SetMeasurableCharacterRanges(characterRanges);

Set up an array to hold the calculated regions:

C#
//
// Set up the array to accept the regions.
Region[] stringRegions = new Region[numChars];
for(int i = 0; i<numChars; i++)
    characterRanges[i] = new CharacterRange(i, 1);

Create a font, and use MeasureCharacterRanges() to calculate the regions for the character ranges.

The regions returned by MeasureCharacterRanges are converted to rectangles by using the GetBounds() function. The rectangle can then be manipulated using offset or any other method to adjust its placement.

In this example, I offset the Y position using a random amount to give wavy text.

C#
//
// The font to use.. 'using' will dispose of it for us
using (Font stringFont = new Font("Times New Roman", 16.0F))
{

    //
    // Get the max width.. for the complete length
    SizeF size = g.MeasureString(measureString, stringFont );

    //
    // Assume the string is in a stratight line, just to work out the 
    // regions. We will adjust the containing rectangles later.
    RectangleF layoutRect = 
        new RectangleF( 0.0f, 0.0f, size.Width, size.Height);

    //
    // Caluclate the regions for each character in the string.
    stringRegions = g.MeasureCharacterRanges(
        measureString,
        stringFont,
        layoutRect,
        stringFormat);

    //
    // Some random offsets, uncomment the DrawRectagle
    // if you want to see the bounding box.
    Random rand = new Random();
    for ( int indx = 0 ; indx < numChars; indx++ )
    {
        Region region = stringRegions[indx] as Region;
        RectangleF rect = region.GetBounds(g);
        rect.Offset( 0f, (float) rand.Next(100) / 10f);
        g.DrawString( measureString.Substring(indx,1), 
              stringFont, Brushes.Yellow, rect, stringFormat );
        // g.DrawRectangle( Pens.Red, Rectangle.Round( rect ));
    }
}

As I said at the beginning, this is not the most efficient code, the calculations could be done outside the drawing routine and cached. However, I hope this demonstrates how easy it is to determine the character positions.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
I've been a developer since 1980 (has it been that long)..

Assembler --> C --> C++ --> C#

A few diversions along the way into Forth, Digital Signal Processing and control systems.

I was born in Scotland, now working in New York City.

Comments and Discussions

 
QuestionWordWrap problem! Pin
Gokhan Erdogdu11-Jan-12 2:45
professionalGokhan Erdogdu11-Jan-12 2:45 
GeneralFinding Character Positions Pin
MOHAMMADALARIQI2-Sep-09 2:54
MOHAMMADALARIQI2-Sep-09 2:54 
GeneralGDI+ Ressources Pin
maddin123421-Aug-04 11:20
maddin123421-Aug-04 11:20 
GeneralI found a way around the limitation :P PinPopular
FocusedWolf16-Aug-06 7:24
FocusedWolf16-Aug-06 7:24 
i made a solution to measuring more then 32 characters

<br />
using System;<br />
using System.Collections.Generic;<br />
using System.ComponentModel;<br />
using System.Data;<br />
using System.Drawing;<br />
using System.Text;<br />
using System.Windows.Forms;<br />
using System.Runtime.InteropServices;<br />
<br />
namespace DrawStringOneCharAtATime<br />
{<br />
    public partial class Form1 : Form<br />
    {<br />
        public Form1()<br />
        {<br />
            InitializeComponent();<br />
        }<br />
<br />
        private Color RandomColor()<br />
        {<br />
            Random random = new Random();<br />
            <br />
            return Color.FromArgb(random.Next(256), random.Next(256), random.Next(256));<br />
        }<br />
<br />
        private Color InvertColor(Color color)<br />
        {<br />
            byte bRed = (byte)~(color.R);<br />
            byte bGreen = (byte)~(color.G);<br />
            byte bBlue = (byte)~(color.B);<br />
<br />
            return Color.FromArgb(bRed, bGreen, bBlue);<br />
            <br />
            //return Color.FromArgb(255 - color.R, 255 - color.G, 255 - color.B);<br />
        }<br />
<br />
        protected override void OnPaint(PaintEventArgs e)<br />
        {<br />
            base.OnPaint(e);<br />
<br />
            if (this.DesignMode)<br />
                return;<br />
<br />
            using (SolidBrush foreColorSolidBrush = new SolidBrush(this.ForeColor))<br />
            using (SolidBrush backColorSolidBrush = new SolidBrush(Color.Yellow))<br />
            {<br />
                string text = "Never send a human to do a wolf's job cause it would be really really really be funny to watch. :p";<br />
<br />
                RectangleF displayRectangle = new RectangleF(0, 40, 200, 200);<br />
<br />
                //GenericDefault, or new StringFormat() do a better job here then StringFormat.TypoGraphic<br />
                //you also need both these format flags.<br />
<br />
<br />
                StringFormat strFormat = StringFormat.GenericTypographic;<br />
                strFormat.FormatFlags =<br />
                    StringFormatFlags.FitBlackBox | <br />
                    StringFormatFlags.NoClip | //vital or the drawn text will look shredded<br />
                    StringFormatFlags.MeasureTrailingSpaces; //so space in end of your text will also get measured<br />
<br />
                CharacterRange[] ranges;<br />
                Region[] charRegions;<br />
<br />
                Color foreColor;<br />
                Color backColor;<br />
                <br />
                for (int index = 0, i; index < text.Length; index += 32)<br />
                {<br />
                    if (text.Length - index < 1) //if index becomes bigger then the text length<br />
                        break;<br />
<br />
                    else if (text.Length - index > 32) //if we're guarenteed 32 characters of bliss<br />
                        ranges = new CharacterRange[32];<br />
<br />
                    else //we got less then 32 characters, but atleast 1<br />
                        ranges = new CharacterRange[text.Length - index];<br />
<br />
                    //get the character ranges for the 32 char-length or less segment of text we're at<br />
                    for (i = 0; i < ranges.Length; i++)<br />
                        ranges[i] = new CharacterRange(index + i, 1);<br />
<br />
                    //setup for measure<br />
                    strFormat.SetMeasurableCharacterRanges(ranges);<br />
<br />
                    //measure it<br />
                    charRegions = e.Graphics.MeasureCharacterRanges(text, this.Font, displayRectangle, strFormat);<br />
<br />
                    //draw text one character at a time<br />
                    for (i = 0; i < charRegions.Length; i++)<br />
                    {<br />
                        //figure out the colors of the text and background<br />
                        foreColor = RandomColor();<br />
                        backColor = InvertColor(foreColor);<br />
<br />
                        foreColorSolidBrush.Color = foreColor;<br />
                        backColorSolidBrush.Color = backColor;<br />
<br />
                        //draw the background<br />
                        e.Graphics.FillRegion(backColorSolidBrush, charRegions[i]);<br />
                        <br />
                        //draw the text                        <br />
                        RectangleF bounds = charRegions[i].GetBounds(e.Graphics);<br />
<br />
                        e.Graphics.DrawString(text[index + i].ToString(), this.Font, foreColorSolidBrush, bounds, strFormat);<br />
                    }<br />
                }<br />
            }<br />
        }<br />
    }<br />
}<br />

GeneralRe: I found a way around the limitation :P Pin
Mewes Kochheim26-Jul-11 13:50
Mewes Kochheim26-Jul-11 13:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.