Flash ActionScript3.0如何生成随机验证码,依据生成验证码的一般原理,先生成一个四位的随机数字或字母(当然也可以六位甚至其它), 然后对每一个字母设置不同的字体,并适当的倾斜,然后生成一张半透明之类状的燥声图片和原文字融合便生成了验证码的图片,原程序如下:
package
{
import fl.motion.Color;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Graphics;
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFormat;
/**
* …
* @author Samson wen & Addis
*/
public class Main extends Sprite
{
private var num:int;
private var vStr:String = “0123456789”
private var color:Array;
private var font:Array;
private var vColor:Array;
private var w:int;
private var h:int;
private var r:int = 15;
public function Main()
{
init();
num = 4;
var s:Sprite = makeFont();
addChild(s);
var b:Bitmap = makeV(w, h);
b.alpha = 0.6;
addChild(b);
}
private function init():void
{
//生成字体颜色数组
color = new Array();
color.push(0x000000);
color.push(0x000066);
color.push(0x330000);
color.push(0x00002F);
//生成字体数组
font = new Array();
font.push(“黑体”);
font.push(“Comic Sans MS”);
font.push(“Arial”);
font.push(“Symbol”);
//生成燥声点的颜色数组
vColor = new Array();
vColor.push(0xFF99FF);
vColor.push(0xFFCCFF);
vColor.push(0xFFCC99);
vColor.push(0x9999FF);
}
//生成随机点燥声
private function makeV(w:int, h:int):Bitmap
{
var bit:BitmapData = new BitmapData(w, h);
var color:int;
var px:int;
var py:int;
var c:int;
for (var i:int = 0; i < 1000; i++)
{
py = Math.random() * h;
px = Math.random() * w;
c = vColor[int(Math.random() * (vColor.length – 1))];
bit.setPixel(px, py, c);
}
return new Bitmap(bit);
}
//生成验证码文字
private function makeFont():Sprite
{
var t:Array = new Array();
var temp:TextField;
var str:String;
var format:TextFormat;
var l:int = 0;
var sprite:Sprite = new Sprite();
for (var i:int = 0; i < num; i++)
{
temp = new TextField();
temp.text = vStr.charAt(int(Math.random() * (vStr.length – 1)));
temp.textColor = 0x000000;
format = new TextFormat();
format.color = color[int(Math.random() * ( color.length – 1 ))];
format.font = font[int(Math.random() * ( font.length – 1 ))];
format.size = 15;
temp.setTextFormat(format);
temp.x = l;
temp.y = setRandom( -5, 5) + 7;
l += temp.textWidth + 5;
temp.selectable = false;
sprite.addChild(temp);
}
w = l + 5;
h = temp.textHeight + 10;
return sprite;
}
private function setRandom(b:Number,e:Number):Number
{
var result:Number;
result = Math.random() * (e – b);
result += b;
return result;
}
}
}