在参考别人相关代码的基础上,博主开发了基于C#的字体设计器,基本实现了常规的字体设计的需要,下面是详细的代码:
Font font = new Font("宋体", 9, FontStyle.Regular); //默认的字体
string[] styleArray = { "常规", "粗体", "斜体", "粗体 倾斜" }; //字体效果
string[] sizeArray = { "8", "9", "10", "11", "12", "14", "16", "18", "20", "22", "24", "26", "28", "36", "48",
"初号", "小初", "一号", "小一", "二号", "小二", "三号", "小三", "四号", "小四", "五号",
"小五", "六号", "小六", "七号", "八号" };
int[] sizeIntArray = { 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 42, 36, 26, 24, 22,
18, 16, 15, 14, 12, 10, 9, 8, 7, 6, 5 };
System.Drawing.Text.InstalledFontCollection collection = new InstalledFontCollection();
FontFamily[] fontFamily = collection.Families;
foreach(var f in fontFamily)
{
if(f.IsStyleAvailable(FontStyle.Regular))
{
listBox1.Items.Add(f.Name);
}
} //将字体名称加入下拉列表
int index = 0;
for (int i = 0; i < listBox1.Items.Count; i++)
{
if(listBox1.Items[i].ToString().Equals("宋体"))
{
index = i;
break;
}
}
for (int i = 0; i < styleArray.Length; i++)
{
listBox2.Items.Add(styleArray[i]);
}
for(int i=0;i<sizeArray.Length;i++)
{
listBox3.Items.Add(sizeArray[i]);
}
textBox1.Text = "宋体";
textBox2.Text = "常规";
textBox3.Text = "9";
listBox1.SetSelected(index, true); //listBox1的默认选中项为宋体
listBox2.SetSelected(0, true); //listBox2的默认选中项为常规
listBox3.SetSelected(1, true); //listBox1的默认选中项为9号字体
label4.Font = font; //示例的文字
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = listBox1.SelectedItem.ToString();
font = new Font(textBox1.Text, fontSize(textBox3.Text), fontStyle(textBox2.Text));
label4.Font = font;
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
textBox2.Text = listBox2.SelectedItem.ToString();
font = new Font(textBox1.Text, fontSize(textBox3.Text), fontStyle(textBox2.Text));
label4.Font = font;
}
private void listBox3_SelectedIndexChanged(object sender, EventArgs e)
{
textBox3.Text = listBox3.SelectedItem.ToString();
font = new Font(textBox1.Text, fontSize(textBox3.Text), fontStyle(textBox2.Text));
label4.Font = font;
}
//设置字形
private FontStyle fontStyle(string value)
{
FontStyle f = new FontStyle();
switch (value)
{
case "常规":
f = FontStyle.Regular;
break;
case "粗体":
f = FontStyle.Bold;
break;
case "斜体":
f = FontStyle.Italic;
break;
case "粗体 倾斜":
f = FontStyle.Bold | FontStyle.Italic;
break;
}
return f;
}
//设置字体大小
private int fontSize(string value)
{
int size = 0;
for(int i=0;i<sizeArray.Length;i++)
{
if(value.Equals(sizeArray[i]))
{
size = sizeIntArray[i];
break;
}
}
return size;
}
下面是运行的效果:

使用C#创建字体设计器
本文介绍了如何基于C#开发一款字体设计器,该设计器能够选择不同的字体、样式和大小,并实时预览效果。通过遍历已安装的字体,将字体名称添加到下拉列表,并提供常规、粗体、斜体等样式选项以及多种字号供用户选择。
605

被折叠的 条评论
为什么被折叠?



