gdi+绘制文本

在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);
   }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值