2015-01-12 67 views
2

编辑如何获得字符串的宽度

图形是从内存中的PDF阅读器,但我不知道如何使用与Graphics类... 不知道什么是E在这个答案Get System.Drawing.Font width?


  • 这是我正在开发的一个库项目 - 而不是Windows窗体。

首先问

尝试使用这种方法来获得字符串的宽度,

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

但得到错误,

的对象引用是必需的非静态字段,方法或适当的TY 'System.Drawing.Graphics.MeasureString(字符串,System.Drawing.Font)'

enter image description here

+0

你调用一个实例方法,就好像它是静态的。 – Ani

+0

这就是我的想法,但我不知道它是什么意思:/ – Mathematics

+0

你需要去了解静态类方法和成员以及它们的实例对应之间的区别。前者基本上是“全球化”的,它们存在一次。后者对于该类别的每个实例都是分开存在的。 –

回答

1

MeasureString不是静态方法。您将需要使用一个Graphics实例来访问它。

例如:

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

如果您要引用System.Windows.Forms的使用TextRenderer类来代替,这会减轻你有一个图形对象。

private void MeasureText() 
{ 
    String text1 = "Some Text"; 
    Font arialBold = new Font("Arial", 16); 
    Size textSize = TextRenderer.MeasureText(text1, arialBold); 
} 

UPDATE:

您可以使用一个假的图像使用图形来衡量一个字符串,因为我们不能在类库使用的createGraphics:

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

++ 1 @红蛇,对不起,我忘了提 - 我需要它在一个库类 – Mathematics

+0

@CustomizedName更新了答案的类库 –