📅  最后修改于: 2023-12-03 15:38:32.289000             🧑  作者: Mango
在C#中,我们可以通过以下步骤为标签中存在的内容设置字体:
using System.Drawing;
using System.Drawing.Text;
Font font = new Font("Arial", 12, FontStyle.Bold);
private void label1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.Clear(label1.BackColor);
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
e.Graphics.DrawString(label1.Text, font, new SolidBrush(label1.ForeColor), e.ClipRectangle, stringFormat);
}
完整的示例代码:
using System;
using System.Drawing;
using System.Drawing.Text;
using System.Windows.Forms;
namespace FontExample
{
public partial class Form1 : Form
{
private Font font = new Font("Arial", 12, FontStyle.Bold);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
label1.Paint += new PaintEventHandler(label1_Paint);
}
private void label1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.Clear(label1.BackColor);
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
e.Graphics.DrawString(label1.Text, font, new SolidBrush(label1.ForeColor), e.ClipRectangle, stringFormat);
}
}
}
这样,我们就可以通过以上步骤来为标签中存在的内容设置字体了。