当前位置:   article > 正文

C#在窗体正中输出文字以及输出文字的画刷使用

C#在窗体正中输出文字以及输出文字的画刷使用

为了在窗体正中输出文字,需要获得输出文字区域的宽和高,这使用MeasureString方法,方法返回值为Size类型;
然后计算输出的起点的x和y坐标,就可以输出了;

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using System.Drawing.Drawing2D;
  11. namespace measure
  12. {
  13. public partial class Form1 : Form
  14. {
  15. private SizeF s1;
  16. private string str1 = "测试用的字符串";
  17. private SolidBrush brush1;
  18. private LinearGradientBrush brush2;
  19. public Form1()
  20. {
  21. InitializeComponent();
  22. }
  23. private void Form1_Paint(object sender, PaintEventArgs e)
  24. {
  25. Graphics g = e.Graphics;
  26. s1 = g.MeasureString(str1, new Font(this.Font.Name,20));
  27. //g.DrawString(str1, new Font(this.Font.Name, 20), Brushes.Blue, (ClientRectangle.Width-s1.Width)/2, (ClientRectangle.Height-s1.Height)/2);
  28. }
  29. private void button1_Click(object sender, EventArgs e)
  30. {
  31. brush1 = new SolidBrush(Color.Green);
  32. Graphics g = Graphics.FromHwnd(this.Handle);
  33. g.DrawString(str1, new Font(this.Font.Name, 20), brush1, 10, 10);
  34. }
  35. private void button2_Click(object sender, EventArgs e)
  36. {
  37. Graphics g = Graphics.FromHwnd(this.Handle);
  38. SizeF size = g.MeasureString(str1, new Font(this.Font.Name, 20));//获取字符串的尺寸
  39. PointF point = new PointF(10, 70);//左上角位置
  40. RectangleF rect = new RectangleF(point, size);//字符串显示的区域
  41. brush2 = new LinearGradientBrush(rect, Color.Red, Color.Blue, LinearGradientMode.Horizontal);
  42. g.DrawString(str1, new Font(this.Font.Name, 20), brush2, point);
  43. }
  44. }
  45. }

 

DrawString的第三个参数是画刷类型;Brushes.Blue,这么写也可以;
如果要自己定义画刷,不能这样,
    Brush brush1 = new Brush();
因为Brush是抽象基类,要使用具体的画刷类;

brush1 = new SolidBrush(Color.Green);
这是实心画刷类;

brush2 = new LinearGradientBrush(rect, Color.Red, Color.Blue, LinearGradientMode.Horizontal);
这是线性渐变画刷类;使用此类需要 System.Drawing.Drawing2D 命名空间;
4个参数是:渐变的范围,渐变的开始颜色,渐变的结束颜色,渐变的方向;

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/111819
推荐阅读
相关标签
  

闽ICP备14008679号