.NET System.Drawing.Font - 获取可用的大小和样式

时间:2011-12-28 20:52:20

标签: c# .net fonts size system.drawing

我有一个允许用户选择字体名称的组合。

第二个应该显示字体的可用大小。第三个必须显示可用的样式。

问题:如何检索System.Drawing.Font支持的大小和样式?

2 个答案:

答案 0 :(得分:1)

您可以使用InstalledFontCollection类检索可用字体,然后按照in this MSDN article显示它们。

InstalledFontCollection installedFontCollection = new InstalledFontCollection();

// Get the array of FontFamily objects.
fontFamilies = installedFontCollection.Families;

// The loop below creates a large string that is a comma-separated
// list of all font family names.

int count = fontFamilies.Length;
for (int j = 0; j < count; ++j)
{
    familyName = fontFamilies[j].Name;
    familyList = familyList + familyName;
    familyList = familyList + ",  ";
}

答案 1 :(得分:0)

我今天试图找到一个好看的字体系列,我使用下面的代码来枚举所有字体系列,并将它们打印在图像中,这样就可以更容易地比较看起来不错的字体。

以下分享:

        Bitmap bitmapImage = new Bitmap(width: 1600, height: 8000);
        using (Graphics g = Graphics.FromImage(bitmapImage))
        {
            var imageRect = new Rectangle(x: 0, y: 0, width: 1600, height: 8000);

            System.Drawing.Text.InstalledFontCollection installedFontCollection = new System.Drawing.Text.InstalledFontCollection();
            FontFamily[] fontFamilies = installedFontCollection.Families;

            var format = new StringFormat();
            format.Alignment = StringAlignment.Near;
            format.LineAlignment = StringAlignment.Near;
            format.FormatFlags = StringFormatFlags.NoWrap;

            int verticalOffset = 0;
            for (int j = 0; j < fontFamilies.Length; ++j)
            {
                using (var font = new Font(fontFamilies[j].Name, 40, FontStyle.Regular, GraphicsUnit.Pixel))
                {
                    // Height
                    var textSize = g.MeasureString(fontFamilies[j].Name, font);
                    int textWidth = (int)Math.Ceiling(textSize.Width + 10);
                    int textHeight = (int)Math.Ceiling(textSize.Height + 10);

                    // Draw text
                    Rectangle textRect = new Rectangle(x: j % 2 == 0 ? 0 : 800, y: verticalOffset, width: textWidth, height: textHeight);
                    g.FillRectangle(new SolidBrush(BackgroundColor), textRect);
                    g.DrawString(fontFamilies[j].Name, font, new SolidBrush(PercentageTextColor), textRect, format);
                    g.Save();

                    if (j % 2 == 1)
                    {
                        verticalOffset += textHeight;
                    }
                }
            }
        }

        bitmapImage.Save(this.Response.OutputStream, ImageFormat.Png);


        // then do whatever you like with this bitmapImage, save it to local, etc.