views:

353

answers:

3

Is is somehow possible to control letter spacing when using Graphics.DrawString? I cannot find any overload to DrawString or Font that would allow me to do so.

            g.DrawString("MyString", new Font("Courier", 44, GraphicsUnit.Pixel), Brushes.Black, new PointF(262, 638));

By letter spacing I mean the distance between letters. With spacing MyString could look like M y S t r i n g if I added enough space.

+3  A: 

That's not supported out of the box. You'll either have to draw each letter individually (hard to get that right) or insert spaces in the string yourself. You can stretch the letters by using Graphics.ScaleTransform() but that looks fugly.

Hans Passant
I was able to just draw out each letter individually.
beckelmw
A: 

It's not supported, but as a hack, you could loop through all the letters in the string, and insert a blank space character between each one. You can create a simple function for it as such:

Edit - I re-did this in Visual Studio and tested - bugs are now removed.

private string SpacedString(string myOldString)
{

            System.Text.StringBuilder newStringBuilder = new System.Text.StringBuilder("");
            foreach (char c in myOldString.ToCharArray())
            {
                newStringBuilder.Append(c.ToString() + ' ');
            }

            string MyNewString = "";
            if (newStringBuilder.Length > 0)
            {
                // remember to trim off the last inserted space
                MyNewString = newStringBuilder.ToString().Substring(0, newStringBuilder.Length - 1);
            }
            // no else needed if the StringBuilder's length is <= 0... The resultant string would just be "", which is what it was intitialized to when declared.
            return MyNewString;
}

Then your line of code above would just be modified as :

          g.DrawString(SpacedString("MyString"), new Font("Courier", 44, GraphicsUnit.Pixel), Brushes.Black, new PointF(262, 638));
David Stratton
Thanks for the code. I ended up being able to just draw out each character individually though.
beckelmw
No problem. Yours is not a bad option, either.
David Stratton
+1  A: 

Alternatively you could use the GDI API function SetTextCharacterExtra(HDC hdc, int nCharExtra) (MSDN documentation):

[DllImport("gdi32.dll", CharSet=CharSet.Auto)] 
public static extern int SetTextCharacterExtra( 
    IntPtr hdc,    // DC handle
    int nCharExtra // extra-space value 
); 

public void Draw(Graphics g) 
{ 
    IntPtr hdc = g.GetHdc(); 
    SetTextCharacterExtra(hdc, 24); //set spacing between characters 
    g.ReleaseHdc(hdc); 

    e.Graphics.DrawString("str",this.Font,Brushes.Black,0,0); 
}  
splattne