【问题标题】:How to set multiple FontStyles when instantiating a font?实例化字体时如何设置多个FontStyles?
【发布时间】:2011-02-18 06:43:11
【问题描述】:

在查看 System.Drawing.Font 类的构造函数时,有一个参数可以传入 System.Drawing.FontStyle 枚举中定义的 FontStyles 之一。

即。 大胆的 斜体 常规的 下划线

并且实例化的对象中有粗体、斜体、下划线等布尔属性,但它们是只读的。

如果我想将我的字体定义为具有多种样式(如粗体和下划线)怎么办?

我该怎么做?

【问题讨论】:

    标签: c# asp.net system.drawing


    【解决方案1】:

    FontStyle 枚举是 Flags 枚举。这意味着它的成员都是 2 的幂,允许您使用二进制 OR 组合它们。

    例如,如果你想要粗体和下划线,你会通过

    FontStyle.Bold | FontStyle.Underline
    

    竖线 (|) 是二元 OR 运算符。

    【讨论】:

    • 工作得很好,谢谢!这些东西对我们这些 Java 爱好者来说都是新概念。
    【解决方案2】:

    在 Font 构造函数中,您可以使用 OR 运算符组合多个 FontStyle:

    Font font = new Font(this.Font, FontStyle.Bold | FontStyle.Underline);
    

    【讨论】:

      【解决方案3】:

      您可以使用类似这样的方法,以避免每种情况出现多个 if:

      //define a font to use.
      Font font;
      
      font = new Font(fontname, fontsize, GraphicsUnit.Pixel);
      
      if (bold)
          font = new Font(font, font.Style ^ FontStyle.Bold);
      if (italic)
          font = new Font(font, font.Style ^ FontStyle.Italic);
      if (underline)
          font = new Font(font, font.Style ^ FontStyle.Underline);
      if (strikeout)
          font = new Font(font, font.Style ^ FontStyle.Strikeout);
      

      【讨论】:

      • 这非常低效...使用 flags 枚举一次设置多个样式。
      猜你喜欢
      • 1970-01-01
      • 2010-12-14
      • 1970-01-01
      • 2012-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-01
      相关资源
      最近更新 更多