using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
drawBmp(lbl1, 4);
}
private void Form1_Click(object sender, EventArgs e)
{
drawBmp(lbl1,4);
}
//生成所有用到的字符和数字集合 得到字符串 str
public string GetAllStr() {
string str = "";
for (int i = 0; i < 10; i++) {
str += i;
}
for (int i = (int)'a'; i <= (int)'z'; i++)
{
str += (char)i;
}
for (int i = (int)'A'; i <= (int)'Z'; i++) {
str += (char)i;
}
return str;
}
//生成随机字符串 ,参数len 控制验证码长度
public string GetRndStr(int len) {
string str2 = "";
string str = GetAllStr();
char[] rndChar = str.ToCharArray();
Random rnd = new Random();
for (int i = 0; i < len; i++) {
int k = rnd.Next(str.Length);
str2+=rndChar[k];
}
return str2;
}
public Font set_font( int numFs) {
Font font = null;
switch (numFs) {
case 0: font = new Font("宋体",16,FontStyle.Bold); break;
case 1: font = new Font("宋体", 16, FontStyle.Italic); break;
case 2: font = new Font("宋体", 16,FontStyle.Regular); break;
default: font = new Font("宋体", 16,FontStyle.Strikeout); break;
}
return Font;
}
/*
* 参数lbl是控件Label的名字,Label控件可改为其他控件,如PictureBox等
* 参数rndNumLen
*/
public void drawBmp(Label lbl, int rndNumLen)
{
Random r = new Random();
string rndStr = GetRndStr(rndNumLen);
Bitmap bmp = new Bitmap(80, 40);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.LightBlue);
g.DrawRectangle(new Pen(Color.Black), 0, 0, 80,40);
Font f = new Font("宋体",16,FontStyle.Bold|~FontStyle.Strikeout&~FontStyle.Underline);
SolidBrush sBrush = new SolidBrush(Color.Red);
StringFormat strFormat=new StringFormat();
strFormat.FormatFlags = StringFormatFlags.NoClip;
char[] rndChar = rndStr.ToCharArray();
for (int i = 0; i < rndNumLen; i++) {
g.DrawString(rndChar[i].ToString(), f, sBrush, 1+20*i, 0, strFormat);
}
/**
* 生成背景上的点 100个
*/
Pen p = new Pen(Color.Green, 10);
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
int x = r.Next(bmp.Width);
int y = r.Next(bmp.Height);
bmp.SetPixel(x,y,Color.Green);
}
}
/**
* 生成背景的线条 2×rndNumLen个
*/
for (int i = 0; i < 2*rndNumLen; i++) {
int x1 = r.Next(bmp.Width);
int y1 = r.Next(bmp.Height);
int x2 = r.Next(bmp.Width);
int y2 = r.Next(bmp.Height);
g.DrawLine(new Pen(Color.Gray), new Point(x1,y1), new Point(x2,y2));
}
/**
* 把图片负载在空间上
*/
lbl.Image = bmp;
}
}
}
0 评论:
发表评论