Using System.Drawing.Font
, is there a way to change the Letter Spacing, just like you can change the Font Size?
I'm looking to increase the letter spacing to fit a specific width.
If this is not possible, are there alternatives to get the desired effect? For example, is there an easy way of having multiple graphics which will fit my specific width?
I don't think DrawString will allow you to specify anything as detailed as the spacing between characters, but I would create a helper function that calculates spacing based on a desired width and then draw each character to fit.
Try this and see how you get on...
public void DrawSpacedText(Graphics g, Font font, Brush brush, PointF point, string text, int desiredWidth)
{
//Calculate spacing
float widthNeeded = 0;
foreach (char c in text)
{
widthNeeded += g.MeasureString(c.ToString(), font).Width;
}
float spacing = (desiredWidth - widthNeeded) / (text.Length - 1);
//draw text
float indent = 0;
foreach (char c in text)
{
g.DrawString(c.ToString(), font, brush, new PointF(point.X + indent, point.Y));
indent += g.MeasureString(c.ToString(), font).Width + spacing;
}
}
You could probably optimise this to make only one call to MeasureString per character. Or even use MeasureCharacterRanges to get an array (which I believe is more accurate anyway)
Edit: Here is an example using MeasureCharacterRanges instead...
public void DrawSpacedText(Graphics g, Font font, Brush brush, PointF point, string text, int desiredWidth)
{
//Calculate spacing
float widthNeeded = 0;
Region[] regions = g.MeasureCharacterRanges(text, font, new RectangleF(point, new SizeF(desiredWidth, font.Height + 10)), StringFormat.GenericDefault);
float[] widths = new float[regions.Length];
for(int i = 0; i < widths.Length; i++)
{
widths[i] = regions[i].GetBounds(g).Width;
widthNeeded += widths[i];
}
float spacing = (desiredWidth - widthNeeded) / (text.Length - 1);
//draw text
float indent = 0;
int index = 0;
foreach (char c in text)
{
g.DrawString(c.ToString(), font, brush, new PointF(point.X + indent, point.Y));
indent += widths[index] + spacing;
index++;
}
}