我有一个组合,允许用户选择字体名称。
第二个应该显示字体的可用大小。第三个必须显示可用的样式。
问题:如何检索 System.Drawing.Font 支持的所选尺寸和样式?
您可以使用 InstalledFontCollection 类来检索可用字体,然后枚举它们,如本 MSDN 文章所示。
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 + ", ";
}
分享如下:
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.
我相信字体系列不仅限于特定的点范围,它们可以设置为任何值。它们是硬编码的。但是,当以点为单位的大小转换为像素时,它必须生成整数值。因此,当您指定“8 分”时。它将转换为“8.25 分”。您可以使用以下函数来获取实际的点大小... 代码:
private float GetActualPoints(float points) return (float) Math.Round(points / 0.75f) * 0.75f; }
“0.75”常数是点/像素(比率)Busy