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.
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));
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.
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);
}
I really do believe that ExtTextOut will resolve your problem. You can use the lpDx parameter to add an array of inter-character distances. Here is the pertinent MSN documentation:
http://msdn.microsoft.com/en-us/library/dd162713%28v=vs.85%29.aspx