在C#中,使用GDI+绘制文本通常涉及到Graphics
类和Font
类。以下是一个简单的示例,展示了如何在Windows窗体应用程序中使用GDI+绘制文本。
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics g = e.Graphics;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
if(font == null)
{
font = new Font("新宋体", 12);
}
if (font1 == null)
{
font1 = new Font("新宋体", 12);
}
// 测量文本大小
SizeF textSize = g.MeasureString(text, font);
SizeF textSize1 = g.MeasureString(text1, font1);
// 根据测量结果计算文本的绘制位置
float x = (this.Width - textSize.Width) / 2; // 水平居中
float x1 = (this.Width - textSize1.Width) / 2; // 水平居中
float y = 1 * (this.Height - textSize.Height) / 4; // 垂直居中
float y1 = 3 * (this.Height - textSize1.Height) / 4; // 垂直居中
textRect = new Rectangle(0, (int)y, (int)(this.Width), (int)(textSize.Height));
textRect1 = new Rectangle(0, (int)y1, (int)(this.Width), (int)(textSize1.Height));
g.DrawString(text, font, brush, x, y);
g.DrawString(text1, font, brush1, x1, y1);
}
Font font;
Brush brush;
Font font1;
Brush brush1;
private void OnDataChanged()
{
font = textFont;
brush = new SolidBrush(TextFontColor);
font1 = text1Font;
brush1 = new SolidBrush(Text1FontColor);
}