Reputation: 7628
Edit
Graphics is from a Pdf in memory, but I am not sure how to use that with Graphics class... Not sure what's e in this answer Get System.Drawing.Font width?
First Question
Trying to get string's width using this method,
public static void GetStringWidth(string measureString)
{
Font stringFont = new Font("Arial", 16);
SizeF stringSize = new SizeF();
stringSize = Graphics.MeasureString(measureString, stringFont);
double width = stringSize.Width;
Console.WriteLine(width);
}
But getting error,
An object reference is required for the non-static field, method, or property 'System.Drawing.Graphics.MeasureString(string, System.Drawing.Font)'
Upvotes: 2
Views: 619
Reputation: 4785
MeasureString is not a static method. You will need to use a Graphics instance to access it.
For example:
private void MeasureString(PaintEventArgs e)
{
string measureString = "Measure String";
Font stringFont = new Font("Arial", 16);
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(measureString, stringFont);
}
If you are referencing System.Windows.Forms use the TextRenderer class instead, this will relieve you of having a Graphics object.
private void MeasureText()
{
String text1 = "Some Text";
Font arialBold = new Font("Arial", 16);
Size textSize = TextRenderer.MeasureText(text1, arialBold);
}
UPDATE:
You can use a fake image to measure a string using Graphics as we cannot use CreateGraphics in a class library:
private void MeasureString()
{
string measureString = "Measure String";
Font font = new Font("Arial", 16);
Image fakeImage = new Bitmap(1,1);
Graphics graphics = Graphics.FromImage(fakeImage);
SizeF size = graphics.MeasureString(measureString, font);
}
Upvotes: 2