Android 随机验证码 v1.0 博客文章链接

package com.example.codepass2;

import java.util.Random;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;

public class Code {
    private static int WIDTH = 140;
    private static int HEIGHT = 50;
    private static String strings_code = "QWEASDZXCVBNFGHRTYUIOPJKLNMqweasdzxcvbnfghrtyuiopjklmn1234567890";
    private static Random random = new Random();
    private static int base_padding_left;
    private static final int base_padding_top = 20;
    private static final int random_padding_left = 23;
    public static String code = "";

    private static int mColor() {
        int red = random.nextInt(256);
        int green = random.nextInt(256);
        int blue = random.nextInt(256);
        return Color.rgb(red, green, blue);
    }

    private static String mCode() {
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            buffer.append(strings_code.charAt(random.nextInt(strings_code
                    .length())));
        }
        return buffer.toString();
    }

    private static void mDraw(Canvas canvas, Paint paint) {
        // TODO Auto-generated method stub
        // TODO Auto-generated method stub
        int color = mColor();
        paint.setColor(color);
        int startX = random.nextInt(WIDTH);
        int startY = random.nextInt(HEIGHT);
        int endX = random.nextInt(WIDTH);
        int endY = random.nextInt(HEIGHT);
        canvas.drawLine(startX, startY, endX, endY, paint);
    }

    public static Bitmap createRandomBitMap() {
        /**
         * - 1 - 生成一组随机数
         */
        code = mCode();
        /**
         * - 2 - 创建位图bitmap,画布canvas,初始化画笔Paint
         */
        Bitmap bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);// 创建指定位图的画布
        Paint paint = new Paint();// 新建画笔
        paint.setTextSize(24);// 设置画笔大小
        base_padding_left = 20;
        // 循环n次(次数是code字符大小)
        for (int i = 0; i < code.length(); i++) {
            int color = mColor();// 随机一个颜色
            paint.setColor(color);// 设置颜色
            paint.setFakeBoldText(false);// 取消字体加粗
            float skewX = random.nextInt(11) / 10;
            skewX = random.nextBoolean() ? skewX : (-skewX);
            paint.setTextSkewX(skewX);// 设置字体倾斜方向(整数左,负数右)
            // 设置一个随机数(用于边距)
            int padding_top = base_padding_top + random.nextInt(20);
            // 绘制这个随机数
            canvas.drawText(code.charAt(i) + "", base_padding_left,
                    padding_top, paint);
            base_padding_left += random_padding_left;
        }
        for (int i = 0; i < 1; i++) {
            mDraw(canvas, paint);
        }
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return bitmap;
    }
}