问题
I have one combo that allows user to select a font name.
The 2nd is supposed to show available sizes of the font. The 3rd has to show available styles.
Question: how can I retrieve the sizes and styles selected System.Drawing.Font supports?
回答1:
You could use the InstalledFontCollection class to retrieve the available fonts and then enumerate them as shown 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 + ", ";
}
回答2:
I was trying to find a good-looking font family today, I use the below code to enumerate all font families, and print them in an image, so that it is easier to compare which looks good.
Shared below:
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.
来源:https://stackoverflow.com/questions/8661181/net-system-drawing-font-get-available-sizes-and-styles