分析:
1.先定义一个string用来接收文字,后面要给这个文字添加gra.DrawString()这个方法添加字体样式
2.在定义一个方法在里面分别添加
(1)验证码里的小点点
(2)验证码里的条纹
(3)Graphics里面添加画板所需要的内容
3.在点击一个文本时改变验证码随机
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;
namespace GDI验证码
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SetCode();
}
Random sj = new Random();
string zhuangwenzi;
private void SetCode()
{
zhuangwenzi = "";
for (int i = 0; i < 4; i++)
{
int nex=sj.Next(0, 2);
if (nex==0)
{
zhuangwenzi+=sj.Next(0,10);
}
if (nex==1)
{
zhuangwenzi +=(char)sj.Next(97,123);
}
}
if (string.IsNullOrWhiteSpace(zhuangwenzi))//如果进来是空的就返回
{
return;
}
//封装的位图,可以在上面画图,和图片一个性质
Bitmap bit = new Bitmap(zhuangwenzi.Length+80,30);
Graphics gra = Graphics.FromImage(bit);//Graphics封装一个GDI+绘图图面,FromImage从指定的Image创建新的Graphics//在图片上获取画布中写的内容
gra.Clear(Color.White);//清除整个绘图并以指定背景色填充
Pen pen = new Pen(Brushes.Red,5);
Rectangle rectangle = new Rectangle(0,0,bit.Width-1,bit.Height-1);//bit.Width-1,bit.Height-1表示矩形大小
//给画布添加矩形框
gra.DrawRectangle(pen,rectangle);
for (int i = 0; i < zhuangwenzi.Length; i++) //线条随机出现,又因为zhuangwenzi的长度是4个所以出现4个线条
{
Pen pen1 = new Pen(Color.FromArgb(sj.Next(255),sj.Next(255),sj.Next(255)),sj.Next(3,5));//sj.Next(3,5)线条的粗细
//给画布加线条线条
gra.DrawLine(pen1,sj.Next(0,bit.Width),sj.Next(0,bit.Height),sj.Next(0,bit.Width),sj.Next(0,bit.Height));//sj.Next(0,bit.Width),sj.Next(0,bit.Height),sj.Next(0,bit.Width),sj.Next(0,bit.Height)表示一条线段的开始位置和结束位置,表示矩形的大小显示
}
//给画布里的添加(一个字体变量名)大的字体样式
//错了 Pen pen2 = new Pen(Color.FromArgb(sj.Next(255), sj.Next(255), sj.Next(255)), sj.Next(5, 7));
gra.DrawString(zhuangwenzi,new Font("",sj.Next(15,20), FontStyle.Bold|FontStyle.Italic),new SolidBrush(Color.FromArgb(sj.Next(255),sj.Next(255),sj.Next(255))),new Point(10,5));//DrawString返回指定的字符串,new Point(10,5)指定坐标
//添加小点点
for (int i = 0; i <zhuangwenzi.Length*20 ; i++)
{
Brush bru = new SolidBrush(Color.FromArgb(sj.Next(255),sj.Next(255),sj.Next(255)));//sj.Next(3,6)小点点的大小
gra.FillEllipse(bru, new Rectangle(sj.Next(bit.Width-1),sj.Next(bit.Height-1),2,2));//
}
pictureBox1.Image = bit;//
}
private void pictureBox1_Click(object sender, EventArgs e)
{
SetCode();
}
private void button1_Click(object sender, EventArgs e)
{
if (zhuangwenzi.ToUpper().Equals(textBox1.Text.ToUpper()))//定义的字符串等于等于盒子里的值
{
MessageBox.Show("验证码正确");
}
else
{
MessageBox.Show("验证码错误");
}
}
}
}