Reputation: 9506
I want to create a Rectangle for text. But I don't know size of string. Now I get size as follow(it is not valid for string with upper case):
var textSize = e.Graphics.MeasureString(text, e.Appearance.Font);
But if my string will be uppercase this function will return wrong value.
How to get the size of the string if the string in uppercase?
Upvotes: 0
Views: 551
Reputation: 5140
MeasureString
works for me. Find the following code.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
MeasureStringMin(e);
}
private void MeasureStringMin(PaintEventArgs e)
{
// Set up string.
string measureString = "MEASURE STRING";
Font stringFont = new Font("Arial", 16);
// Measure string.
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(measureString, stringFont);
// Draw rectangle representing size of string.
e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);
// Draw string to screen.
e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));
}
}
Upvotes: 5
Reputation: 6481
From Msdn
To obtain metrics suitable for adjacent strings in layout (for example, when implementing formatted text), use the MeasureCharacterRanges method or one of the MeasureString methods that takes a StringFormat, and pass GenericTypographic. Also, ensure the TextRenderingHint for the Graphics is AntiAlias.
Upvotes: 1