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

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

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace measure
{
    public partial class Form1 : Form
    {
        private SizeF s1;
        private string str1 = "测试用的字符串";
        private SolidBrush brush1;
        private LinearGradientBrush brush2;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            s1 = g.MeasureString(str1, new Font(this.Font.Name,20));
            //g.DrawString(str1, new Font(this.Font.Name, 20), Brushes.Blue, (ClientRectangle.Width-s1.Width)/2, (ClientRectangle.Height-s1.Height)/2);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            brush1 = new SolidBrush(Color.Green);
            Graphics g = Graphics.FromHwnd(this.Handle);
            g.DrawString(str1, new Font(this.Font.Name, 20), brush1, 10, 10);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Graphics g = Graphics.FromHwnd(this.Handle);
            SizeF size = g.MeasureString(str1, new Font(this.Font.Name, 20));//获取字符串的尺寸
            PointF point = new PointF(10, 70);//左上角位置
            RectangleF rect = new RectangleF(point, size);//字符串显示的区域
            brush2 = new LinearGradientBrush(rect, Color.Red, Color.Blue, LinearGradientMode.Horizontal);
            g.DrawString(str1, new Font(this.Font.Name, 20), brush2, point);
        }
    }
}

C#在窗体正中输出文字以及输出文字的画刷使用_第1张图片 

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个参数是:渐变的范围,渐变的开始颜色,渐变的结束颜色,渐变的方向;

C#在窗体正中输出文字以及输出文字的画刷使用_第2张图片

你可能感兴趣的:(.Net,c#,开发语言,画刷,MeasureString)