C# Drawstring Letter Spacing

只谈情不闲聊 提交于 2019-11-28 07:11:47

问题


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.


回答1:


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.




回答2:


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



回答3:


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



回答4:


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



来源:https://stackoverflow.com/questions/2969143/c-sharp-drawstring-letter-spacing

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