1. 程式人生 > >史上最簡單的生成驗證碼

史上最簡單的生成驗證碼

話不多說,直接上程式碼

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);          
}

至此,所有程式碼已經寫完,是不是非常簡單!!!