/// <summary>
/// 绘制验证码的方法
/// </summary>
void SetCode()
{
//默认验证码
string code = "2wa4";
code = code.Trim();
if (String.IsNullOrEmpty(code))
{
return;
}
//验证码大小宽65,高20
Bitmap image = new Bitmap(65, 20);
//创建绘图对象Graphics
Graphics graphics = Graphics.FromImage(image);
//随机
Random r = new Random();
graphics.Clear(Color.White);
//绘制四条随机出现的线
for (int i = 0; i < 4; i++)
{
int x1 = r.Next(image.Width);
int y1 = r.Next(image.Height);
int x2 = r.Next(image.Width);
int y2 = r.Next(image.Height);
graphics.DrawLine(new Pen(Brushes.Black, 1), new Point(x1, y1), new Point(x2, y2));
}
this.BackgroundImage = image;
this.BackgroundImageLayout = ImageLayout.Center;
graphics.DrawRectangle(new Pen(Brushes.Black), 0, 0, image.Width - 1, image.Height - 1);
graphics.DrawString(code, new Font("微软雅黑", 12, FontStyle.Bold), Brushes.Red, 8, -2);
}
//第二种
namespace _03GDI绘图
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SetCodeImage();
}
private void button1_Click(object sender, EventArgs e)
{
SetCodeImage();
}
void SetCodeImage()
{
//string code = "";
//code = code.Trim();
string code = MakeCode(4);
if (String.IsNullOrEmpty(code))
{
return;
}
//制作一张图片
Bitmap image = new Bitmap((int)Math.Ceiling(code.Length*30.0),40);
Graphics grap =Graphics.FromImage(image);
Random r = new Random();
grap.Clear(Color.White);
for (int i = 0; i < 4; i++)
{
int x1 = r.Next(image.Width);
int y1 = r.Next(image.Height);
int x2 = r.Next(image.Width);
int y2 = r.Next(image.Height);
grap.DrawLine(new Pen(Color.Black,2),new Point(x1,y1),new Point(x2,y2));
}
grap.DrawString(code,new Font("楷体",30,FontStyle.Bold),Brushes.Red,2,2);
this.BackgroundImage = image;
this.BackgroundImageLayout = ImageLayout.Center;
grap.DrawRectangle(new Pen(Color.Black), 0, 0, image.Width-1 , image.Height-1);
}
private static string MakeCode(int codeLen)
{
if (codeLen < 1)
{
return string.Empty;
}
int number;
StringBuilder CheckCode = new StringBuilder();
Random r= new Random();
for (int index = 0; index < codeLen; index++)
{
number =r.Next();
if (number % 2 == 0)
{
//生成数字
CheckCode.Append((char)('0' + (char)(number % 10)));
}
else
{
//生成字母
CheckCode.Append((char)('A' + (char)(number % 26)));
}
}
return CheckCode.ToString();
}
}
}