C# Drawstring Letter Spacing

自古美人都是妖i 提交于 2019-11-29 13:33:38

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); 
}  

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));

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!