代码之家  ›  专栏  ›  技术社区  ›  ScottG

如何将字符串长度转换为像素单位?

  •  25
  • ScottG  · 技术社区  · 16 年前

    我有一根这样的绳子:

    string s = "This is my string";
    

    我正在创建Telerik报告,我需要定义 textbox 这就是我绳子的宽度。但是,大小属性需要设置为一个单位(像素、点、英寸等)。如何将字符串长度转换为像素,以便设置宽度?

    编辑: 我试图获取对图形对象的引用,但这是在继承自 Telerik.Reporting.Report .

    5 回复  |  直到 10 年前
        1
  •  56
  •   shA.t Rami Jamleh    10 年前

    不使用控件或窗体:

    using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(new Bitmap(1, 1)))
    {
        SizeF size = graphics.MeasureString("Hello there", new Font("Segoe UI", 11, FontStyle.Regular, GraphicsUnit.Point));
    }
    

    或者在VB.NET中:

    Using graphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(New Bitmap(1, 1))
        Dim size As SizeF = graphics.MeasureString("Hello there", New Font("Segoe UI", 11, FontStyle.Regular, GraphicsUnit.Point))
    End Using
    
        2
  •  18
  •   Wachburn    13 年前
    Size textSize = TextRenderer.MeasureText("How long am I?", font);
    
        3
  •  9
  •   shA.t Rami Jamleh    10 年前

    在这种情况下,我通常使用肮脏但简单的方法:

    • 我添加了一个不可见的 Label 它的 AutoSize 财产是 true - 肮脏的工作 -
    • 当我想拥有 Width 对于特定的字符串,我将其设置为 Label.Text .
    • 这个 宽度 标签 会给我正确的值。
        4
  •  4
  •   duffymo    16 年前

    也取决于字体。字符串长度不够。

        5
  •  4
  •   shA.t Rami Jamleh    10 年前

    可以创建图形对象的实例,使用 MeasureString() 方法。但您需要将字体名称、字体大小和其他信息传递给它。