本文是关注如何使用Graphics生成验证码样式,效果如图:
1. 用C#创建一个基于Windows Form的应用程序;
2. 拖一个【pictureBox】到窗体中,双击该控件,在Click动作中添加,每次点击效果不一样:
private void pictureBox1_Click(object sender, EventArgs e) { Random r = new Random(); string[] fontString = new string[] { "黑体", "幼圆", "楷体", "华文仿宋"}; Color[] colorArray = new Color[] { Color.Blue, Color.Black, Color.Yellow, Color.Green}; string strNumbers = ""; Bitmap bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height); Graphics g = Graphics.FromImage(bmp); //生成4个数字、点、字体、颜色,画出来 for(int i=0; i<4; i++) { strNumbers += r.Next(0, 9); Point pt = new Point(i * 20, 0); g.DrawString(strNumbers[i].ToString(), new Font(fontString[i], 20), new SolidBrush(colorArray[r.Next(3)]), pt); } //随机画几条直线 for (int i = 0; i < 10; i++ ) { Point p1 = new Point(r.Next(bmp.Width), r.Next(bmp.Height)); Point p2 = new Point(r.Next(bmp.Width), r.Next(bmp.Height)); g.DrawLine(new Pen(colorArray[i % 4]), p1, p2); } //随机画一些点 for (int i = 0; i < 200; i++ ) { bmp.SetPixel(r.Next(bmp.Width), r.Next(bmp.Height), colorArray[i % 4]); } pictureBox1.Image = bmp; }