网站解析,安徽省经工建设集团公司网站,成都企业排名,做eso哪家网站好为了在窗体正中输出文字#xff0c;需要获得输出文字区域的宽和高#xff0c;这使用MeasureString方法#xff0c;方法返回值为Size类型#xff1b; 然后计算输出的起点的x和y坐标#xff0c;就可以输出了#xff1b;
using System;
using System.Collections.Generic;
…为了在窗体正中输出文字需要获得输出文字区域的宽和高这使用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);}}
} 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个参数是渐变的范围渐变的开始颜色渐变的结束颜色渐变的方向