【问题标题】:Can't convert string to font in C#无法在 C# 中将字符串转换为字体
【发布时间】:2017-09-11 14:36:14
【问题描述】:
TypeConverter converter = TypeDescriptor.GetConverter(typeof(Font));
Font font = (Font)converter.ConvertFromString("[Font: Name=Arial, Size=48, Units=3, GdiCharSet=0, GdiVerticalFont=False]");
this.Font = font;

Error => System.ArgumentException: 'Value of 'Size=48, Units=3, GdiCharSet=0, GdiVerticalFont=False]' 对于 'units' 无效。'

【问题讨论】:

  • documentation 中的示例来看,该字符串的格式似乎不正确,您能否详细说明您是如何使用该格式的?
  • msdn.microsoft.com/en-us/library/… 你的字符串看起来不对
  • 请注意Font.ToString() 不会返回适合FontConverter 的字符串。使用FontConverter 也可以将字体转换为字符串以获取可以转换回来的内容。特别是,您可能想要这个字符串:"Arial; 48pt"
  • 请注意,这可能取决于文化。因此,请确保您在相同的文化中来回转换它。 (Lasse 示例中的分号是可以在不同文化之间改变的字符)。

标签: c#


【解决方案1】:

这里的问题是您使用Font.ToString() 方法生成了FontConverter 不支持的字符串。

相反,您应该使用FontConverter 来生成字符串,然后您会得到一个如下所示的字符串:

Arial; 12pt; style=Bold

通过其.ToString() 方法运行的相同字体对象给出:

[Font: Name=Arial, Size=12, Units=3, GdiCharSet=1, GdiVerticalFont=False]

对于您的特定字符串,您应该改用此字符串:

"Arial; 48pt"

【讨论】:

  • 请注意,这可能取决于文化。因此,请确保您在相同的文化中来回转换它。 (示例字符串中的分号是可以在不同文化之间改变的字符)。
【解决方案2】:

尝试以下方法:

TypeConverter converter = TypeDescriptor.GetConverter(typeof(Font));
Font font = (Font)converter.ConvertFromString("Arial, 48pt");
this.Font = font;

【讨论】:

  • 感谢您的回答。
【解决方案3】:

Microsoft 没有很好地记录这一点。

但是,如果您查看reference source for FontConverter,您会看到以下内容:

internal class UnitName {

    internal string name; 

    internal GraphicsUnit unit;

    internal static readonly UnitName[] names = new UnitName[] {
            new UnitName("world", GraphicsUnit.World), // made up
            new UnitName("display", GraphicsUnit.Display), // made up
            new UnitName("px", GraphicsUnit.Pixel),
            new UnitName("pt", GraphicsUnit.Point),
            new UnitName("in", GraphicsUnit.Inch),
            new UnitName("doc", GraphicsUnit.Document), // made up
            new UnitName("mm", GraphicsUnit.Millimeter),
        };


    internal UnitName(string name, GraphicsUnit unit) {
        this.name = name;
        this.unit = unit;
    }
}

所以看起来您应该将单位指定为以下之一:

world | display | px | pt | in | doc | mm

您需要将这些值之一添加到 size 值。源代码中的注释说:

text is expected to have a format like " 8,25pt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多