android客户端生成本地验证码主要用来限制用户随意按请求按钮,其实该示例也是来对自定义view的练练手而已,先给出效果图吧
其中可定制:
*干扰线数目
*干扰点数目
*背景颜色
*验证码字体大小及字数
相信以上可以满足一般的需要了吧,不够的话可自行添加,下面就来讲实现的步骤了
继承view,重写构造方法,并初始化所需参数
public class ValidationCode extends View {
private Paint mTextPaint;//文字画笔
private Paint mPointPaint;//干扰点画笔
private Paint mPathPaint;//干扰线画笔
private Paint mBitmapPaint;//Bitmap图画笔
private String mCodeString;//随机验证码
private int mCodeCount;//验证码位数
private float mTextSize;//验证码字符大小
private int mPointNumber;//干扰点数目
private int mLineNumber;//干扰线数目
private int mBackGround;//背景颜色
private float mTextWidth;//验证码字符串的显示宽度
private static int mWidth;//控件的宽度
private static int mHeight;//控件的高度
private static Random mRandom = new Random();
private Bitmap bitmap = null;//生成验证码图片
public ValidationCode(Context context) {
this(context, null);
}
public ValidationCode(Context context, AttributeSet attrs) {
super(context, attrs);
getAttrValues(context, attrs);
init();
}
/**
* 获取布局文件中的值
*/
private void getAttrValues(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ValidationCode);
mCodeCount = typedArray.getInteger(R.styleable.ValidationCode_CodeCount, 4);
mPointNumber = typedArray.getInteger(R.styleable.ValidationCode_PointNumber, 100);
mLineNumber = typedArray.getInteger(R.styleable.ValidationCode_LineNumber, 2);
mTextSize = typedArray.getDimension(R.styleable.ValidationCode_CodeTextSize, 20);
mBackGround