C#利用GDI绘图工具绘制验证码
程序运行效果图:
该程序由一个pictureBox控件和一个button控件组成,点击button实现验证码刷新功能,使用GDI进行绘制,通过随机数生成验证码内容,字体,颜色等(这些东西可以根据自我需求进行删减或者添加),以下为主体部分代码(button控件click事件代码),*****后方有程序全部代码*****
private void button1_Click(object sender, EventArgs e) { stringstr=null ;
Random Ran = new Random(); char[]
s
=
{'0','1','2','3','4','5','6','7','8','9','q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m','Q','W','E','R','T','Y','U','I','O','P','L','K','J','H','G','F','D','S','A','Z','X','C','V','B','N','M' };
for (inti = 0; i<= 4; i++) { int a=Ran.Next(0,61); char b=s[a]; str+= b; }
Bitmap btm = new Bitmap(178,67); Graphics g = Graphics.FromImage(btm); pictureBox1.Image = btm; for (inti = 0; i<= 4; i++) {
Point p=new Point(i*32,10);
string[] point = {\微软雅黑\华文行楷\楷体\隶书\
黑体\仿宋\宋体\
Color[]
color
=
{Color.Red,Color.Green,Color.Brown,Color.Blue,Color.SpringGreen };
g.DrawString(str[i].ToString(), new Font(point[Ran.Next(0, 6)], 38,
FontStyle.Bold), new SolidBrush(color[Ran.Next(0, 4)]), p);
} for (inti = 0; i<= 50; i++) {
Point
p1
=
new
Point(Ran.Next(0,pictureBox1.Width),Ran.Next(0,pictureBox1.Height));
Point p2 = new Point(Ran.Next(0,
pictureBox1.Width), Ran.Next(0, pictureBox1.Height));
g.DrawLine( new Pen(Brushes.LemonChiffon),p1,p2); }
for (inti = 0; i<= 500; i++)
{
Point p3 = new Point(Ran.Next(0,
pictureBox1.Width), Ran.Next(0, pictureBox1.Height));
btm.SetPixel(p3.X,p3.Y,Color.Black); }
}
全部程序代码如下: