有没有办法在 C# 中设置 Windows 窗体控件的字体,以接受逗号分隔的字体列表?我想要类似于浏览器解释 CSS 字体系列的方式,它沿着列表向下移动,直到找到计算机上安装的第一个字体。
示例:
string fontList = "Obscure Font1, Obscure Font2, Verdana"
textBox1.Font = new Font( FontFamilyFromHtml(fontList), FontStyle.Bold);
.NET 中是否内置了任何内容,或者您是否需要创建一种方法来用逗号分割字符串,然后测试每个字体的已安装字体列表,直到找到匹配项?
最佳答案
没有开箱即用的 API 调用,因此您必须拆分字符串并搜索已安装的字体。
这是一个使用 InstalledFontCollection 的实现为此:
private FontFamily FindFontByCSSNames(string cssNames)
{
string[] names = cssNames.Split(',');
System.Drawing.Text.InstalledFontCollection installedFonts = new System.Drawing.Text.InstalledFontCollection();
foreach (var name in names)
{
var matchedFonts = from ff in installedFonts.Families where ff.Name == name.Trim() select ff;
if (matchedFonts.Count() > 0)
return matchedFonts.First();
}
// No match, return a default
return new FontFamily("Arial");
}
关于c# - 如何从 html/css 样式字符串(即 : Futura, Verdana、Arial)在 C# winforms 控件(例如 TextBox)中设置 FontFamily,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14077168/