史上最简单的生成验证码

话不多说,直接上代码

public class CodeView {

    private CodeView(){}

    private static class Builder {
        private static final CodeView CODE_VIEW = new CodeView();
    }

    public static CodeView getInstance() {
        return Builder.CODE_VIEW;
    }

    // 验证码默认的宽度,单位PX (AndroidUtil.dip2px(110) 此处是DP转PX,代码就不贴了)
    private static final int DEFAULT_WIDTH = AndroidUtil.dip2px(110);
    // 验证码默认的高度,单位PX
    private static final int DEFAULT_HEIGHT = AndroidUtil.dip2px(40);
    // 验证码默认的个数
    private static final int LENGTH = 4;

    private int width = DEFAULT_WIDTH;
    private int height = DEFAULT_HEIGHT;

    // 验证码的个数
    private int codeLength = LENGTH;

    private String[] code;

    private Random random = new Random();

    /**
     * 设置验证码的个数 1 <= length <= 6
     */
    public CodeView setCodeLength(int length) {
        if (length <= 0) {
            length = 1;
        }
        if (length > 6) {
            length = 6;
        }
        this.codeLength = length;
        return this;
    }

    /**
     * 设置验证码的宽
     * @param width 单位:PX
     */
    public CodeView setCodeWidth(int width) {
        this.width = width;
        return this;
    }

    /**
     * 设置验证码的高
     * @param height 单位:PX
     */
    public CodeView setCodeHeight(int height) {
        this.height = height;
        return this;
    }

    /**
     * 得到验证码
     */
    public String getCode() {
        StringBuilder sb = new StringBuilder();
        if (code != null && code.length > 0) {
            for (String str : code) {
                sb.append(str);
            }
            return sb.toString();
        }
        throw new RuntimeException("Please call \"createCode()\" method first");
    }

    public Bitmap createCode() {
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        getRandomCode();
        // 使用抗锯齿画验证码
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        Paint textPaint = new Paint();
        int leftPadding = 0;
        for (int i = 0; i < codeLength; i++) {
            Rect rect = new Rect();
            paint.setColor(getRandomColor());
            paint.setTextSize(getRandomTextSize());
            // 获取单个Code的宽,高
            paint.getTextBounds(code[i], 0, code[i].length(), rect);

            leftPadding = leftPadding + width / (codeLength + 1);
            canvas.drawText(code[i], leftPadding, getRandomHeight() + rect.height() / 2, paint);
            // 控制验证码线条的数量
            if (i % 2 == 0) {
                drawLine(canvas, textPaint);
            }
        }
        // 保存画布
        canvas.save(Canvas.CLIP_SAVE_FLAG);
        canvas.restore();
        return bitmap;
    }

    private void getRandomCode() {
        code = new String[codeLength];
        for (int i = 0; i < codeLength; i++) {
            String str = Content.CODE_TEXT[random.nextInt(Content.CODE_TEXT.length)];
            code[i] = str;
        }
    }

    private int getRandomColor() {
        return Content.CODE_COLOR[random.nextInt(Content.CODE_COLOR.length)];
    }

    private int getRandomTextSize() {
        return Content.CODE_TEXT_SIZE[random.nextInt(Content.CODE_TEXT_SIZE.length)];
    }

    private int getRandomHeight() {
        int r = random.nextInt(codeLength);
        if (r % 2 == 0) {
            return height / 2;
        } else {
            return height / 3;
        }
    }

    // 随机生成验证码的线条
    private void drawLine(Canvas canvas, Paint paint) {
        int color = getRandomColor();
        int startX = random.nextInt(width);
        int startY = random.nextInt(height);
        int stopX = random.nextInt(width);
        int stopY = random.nextInt(height);
        paint.setStrokeWidth(2);
        paint.setColor(color);
        canvas.drawLine(startX, startY, stopX, stopY, paint);
    }
}

Content中的代码,主要是验证码的一些内容

public class Content {

   public static final String[] CODE_TEXT = {
            "0","1","2","3","4","5","6","7","8","9",
            "a","b","c","d","e","f","g","h","i","j",
            "k","l","m","n","o","p","q","r","s","t",
            "u","v","w","x","y","z","A","B","C","D",
            "E","F","G","H","I","J","K","L","M","N",
            "O","P","Q","R","S","T","U","V","W","X",
            "Y","Z"};

    // 验证码的大小
    public static final int[] CODE_TEXT_SIZE = {
            40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70 };

    // 验证码的颜色
    public static final int[] CODE_COLOR = {
            Toaster.getContext().getResources().getColor(R.color.red),
            Toaster.getContext().getResources().getColor(R.color.pink),
            Toaster.getContext().getResources().getColor(R.color.violet),
            Toaster.getContext().getResources().getColor(R.color.blue),
            Toaster.getContext().getResources().getColor(R.color.green),
            Toaster.getContext().getResources().getColor(R.color.gray),
            Toaster.getContext().getResources().getColor(R.color.black),
            Toaster.getContext().getResources().getColor(android.R.color.holo_orange_dark)
    };
}

在Activity中或Fragment中使用如下

ImageView codeView = (ImageView) findViewById(R.id.pic);
// 生成验证码代码
int w = AndroidUtil.dip2px(120);
int h = AndroidUtil.dip2px(50);
Bitmap code = CodeView.getInstance()
                    .setCodeLength(6) // 设置验证码的数量
                    .setCodeWidth(w)
                    .setCodeHeight(h)
                    .createCode();
codeView.setImageBitmap(code);                      

判断验证码输入是否正确

if (!CodeView.getInstance().getCode().equals(codeText.getText().toString())) {
    Log.e("code","输入错误,请重新输入");
    Bitmap code = CodeView.getInstance().createCode();
    codeView.setImageBitmap(code);          
}

至此,所有代码已经写完,是不是非常简单!!!

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值