只为了记录下自己的学习历程,方便日后查看
现在开始言归正传,以下为其完整代码附上
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 _06GDI_绘制验证码
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void pictureBox1_Click(object sender, EventArgs e)
{
//用户生成随机码
Random r = new Random();
//用于遍历验证码的序列
string str="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
//存储验证码
string code = "";
for (int i = ; i < ; i++)
{
//随机从字符串序列中随机生成一个字符,并将其添加到验证码中
code += str[r.Next(,str.Length)]; }
//创建位图对象,Bitmap继承于Image类
Bitmap bitimage = new Bitmap(,);
Graphics gra = Graphics.FromImage(bitimage);
for (int i = ; i < ; i++)
{
//通过点,设置每个字体的宽度
Point point = new Point(i*,);
//字体数组,用于验证码中产生不同随机字体,
string[] fonts = { "幼圆", "宋体", "仿宋", "楷体", "Times New Roman" };
//颜色数组,用于验证码中产生不同颜色的字。
Color[] colors = {Color.Black,Color.Blue,Color.Brown,Color.Chocolate,Color.DarkSlateBlue};
//将生成的验证码字符通过GDI对象绘制出,调用DrawString()方法
gra.DrawString(code[i].ToString(),new Font(fonts[r.Next()],,FontStyle.Bold),new SolidBrush(colors[r.Next()]),point); }
//在验证码上添加部分线,使其不那么清晰 for (int i = ; i < ; i++)
{
Point p1=new Point(r.Next(bitimage.Width),r.Next(bitimage.Height));
Point p2=new Point(r.Next(bitimage.Width),r.Next(bitimage.Height));
Pen pen = new Pen(Brushes.Blue);
gra.DrawLine(pen,p1,p2);//绘制线条
}
//在验证码上添加部分点,使其不那么清晰
for (int i = ; i < ; i++)
{
Point p = new Point(r.Next(bitimage.Width),r.Next(bitimage.Height));
bitimage.SetPixel(p.X, p.Y, Color.Black);//绘制点 }
picCon.Image = bitimage;//将所绘制的验证码添加到picboxs上 }
}
}
GDI+ 绘制验证码
以下为运行结果图