7.利用GDI+绘制文本
来源:http://www.cnblogs.com/kiny/articles/2508481.html
//s:要绘制的字符串。 //font:System.Drawing.Font,它定义字符串的文本格式。 //brush:System.Drawing.Brush,它确定所绘制文本的颜色和纹理。 //point:System.Drawing.PointF 结构,它指定所绘制文本的左上角。 DrawString(string s, Font font, Brush brush, PointF point) DrawString(string s, Font font, Brush brush, float x, float y) DrawString(string s, Font font, Brush brush, PointF point, StringFormat format) DrawString(string s, Font font, Brush brush, float x, float y, StringFormat format) //layoutRectangle:System.Drawing.RectangleF 结构,它指定所绘制文本的位置。 DrawString(string s, Font font, Brush brush, RectangleF layoutRectangle) DrawString(string s, Font font, Brush brush, RectangleF layoutRectangle, StringFormat format)
1.验证码的例子
private void Form1_Paint(object sender, PaintEventArgs e) { //创建画板从Paint事件中的直接引用Graphics对象 Graphics graphics = e.Graphics; graphics.Clear(Color.Black); //验证码长度 int intCheckCodeLength = 4; //先绘制一个现实验证码的区域 Rectangle rect = new Rectangle(200, 100, 220, 50); //在黑色的绘制表面上,填充一个白色的矩形背景 Brush brushRect = Brushes.White; graphics.FillRectangle(brushRect, rect); //验证码字符 string[] strLetters =
{ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; //字体名字 string[] sbFonts = { "Arial", "Arial Black", "Bauhaus 93", "Consolas", "Courier New" }; //每个字符X的位置 float floatOffset = 50; //循环长度为验证码长度 for (int i = 0; i < intCheckCodeLength; i++) { Random rand = new Random(Guid.NewGuid().GetHashCode()); int rndFont = rand.Next(0, sbFonts.Length - 1);//随机取一个字体的下标 int rndLetter = rand.Next(0, 26);//随机取一个字符的下标 Font font = new Font(sbFonts[rndFont].ToString(), 32.0f);//字体 SolidBrush brush = new SolidBrush(Color.FromArgb(rand.Next(255), rand.Next(255), rand.Next(255))); graphics.DrawString(strLetters[rndLetter], font, brush, new PointF(205.0f + i * floatOffset, 100.0f)); }
2.控制文本绘制方向
在绘制Y轴标签的时候,希望标签是靠近轴来向左分布。
//画标签 StringFormat drawFormat = new StringFormat(); drawFormat.FormatFlags=StringFormatFlags.DirectionRightToLeft; e.Graphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat);