Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自訂 View 實作:在本機產生驗證碼

編輯:關於 Android 程式設計

在 App 本機產生驗證碼,主要目的是避免使用者無腦連點「請求」按鈕。這個範例同時也是拿來練手自訂 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  = typedArray.getColor(R.styleable.ValidationCode_BackGround, Color.WHITE);
        typedArray.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec));
    }

    /** 初始化各支畫筆 */
    private void init() {
        mCodeString = getValidationCode(mCodeCount); // 先產生隨機驗證碼

        mTextPaint = new Paint();
        mTextPaint.setStrokeWidth(3);
        mTextPaint.setTextSize(mTextSize);

        mPointPaint = new Paint();
        mPointPaint.setStrokeWidth(4);
        mPointPaint.setStrokeCap(Paint.Cap.ROUND); // 端點為圓形

        mPathPaint = new Paint();
        mPathPaint.setStrokeWidth(5);
        mPathPaint.setColor(Color.GRAY);
        mPathPaint.setStyle(Paint.Style.STROKE);   // 空心畫筆
        mPathPaint.setStrokeCap(Paint.Cap.ROUND);

        mBitmapPaint = new Paint();
        mBitmapPaint.setColor(Color.RED);

        mTextWidth = mTextPaint.measureText(mCodeString); // 字串顯示寬度
    }
}

getAttrValues 用來讀取自訂屬性,因此必須在 values 底下新增 attrs.xml 並宣告這些屬性:

<resources>
    <declare-styleable name="ValidationCode">
        <attr name="CodeCount" format="integer" />
        <attr name="PointNumber" format="integer" />
        <attr name="LineNumber" format="integer" />
        <attr name="CodeTextSize" format="dimension" />
        <attr name="BackGround" format="color" />
    </declare-styleable>
</resources>

onMeasure 則是拿來決定自訂 View 尺寸的入口,透過 setMeasuredDimension 告訴系統實際要佔多大。這裡依字串寬度推算寬高:

/** 重新定義 view 的寬高 */
private int measureWidth(int measureSpec) {
    int result = 0;
    int specMode = MeasureSpec.getMode(measureSpec);
    int specSize = MeasureSpec.getSize(measureSpec);
    if (specMode == MeasureSpec.EXACTLY) {
        result = specSize;
    } else {
        result = (int) (mTextWidth * 2.0f);
        if (specMode == MeasureSpec.AT_MOST) {
            result = Math.min(result, specSize);
        }
    }
    return result;
}

private int measureHeight(int measureSpec) {
    int result = 0;
    int specMode = MeasureSpec.getMode(measureSpec);
    int specSize = MeasureSpec.getSize(measureSpec);
    if (specMode == MeasureSpec.EXACTLY) {
        result = specSize;
    } else {
        result = (int) (mTextWidth / 1.5f);
        if (specMode == MeasureSpec.AT_MOST) {
            result = Math.min(result, specSize);
        }
    }
    return result;
}

二、產生驗證碼內容與干擾元素

驗證碼字串由大小寫字母與數字隨機混合;干擾點與干擾線則各自畫上去:

/** 取得驗證碼 */
public static String getValidationCode(int length) {
    String val = "";
    Random random = new Random();
    for (int i = 0; i < length; i++) {
        // 隨機決定這個位置是字母還是數字
        String code = random.nextInt(2) % 2 == 0 ? "char" : "num";
        if ("char".equalsIgnoreCase(code)) {
            int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; // 大寫或小寫
            val += (char) (choice + random.nextInt(26));
        } else if ("num".equalsIgnoreCase(code)) {
            val += String.valueOf(random.nextInt(10));
        }
    }
    return val;
}

/** 畫干擾點 */
private static void drawPoint(Canvas canvas, Paint paint) {
    PointF pointF = new PointF(mRandom.nextInt(mWidth) + 10, mRandom.nextInt(mHeight) + 10);
    canvas.drawPoint(pointF.x, pointF.y, paint);
}

/** 畫干擾線 */
private static void drawLine(Canvas canvas, Paint paint) {
    int startX = mRandom.nextInt(mWidth);
    int startY = mRandom.nextInt(mHeight);
    int endX   = mRandom.nextInt(mWidth);
    int endY   = mRandom.nextInt(mHeight);
    canvas.drawLine(startX, startY, endX, endY, paint);
}

/** 繪製驗證碼並回傳 Bitmap */
private Bitmap generateValidate() {
    if (bitmap != null && !bitmap.isRecycled()) {
        bitmap.recycle();
        bitmap = null;
    }

    Bitmap sourceBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(sourceBitmap);

    canvas.drawColor(mBackGround); // 背景

    // 逐字畫上驗證碼,每個字給一點隨機傾斜與顏色
    int length = mCodeString.length();
    float charLength = mTextWidth / length;
    for (int i = 1; i <= length; i++) {
        int offsetDegree = mRandom.nextInt(15);
        // 只會產生 0 和 1:1 為正旋轉,否則負旋轉
        offsetDegree = mRandom.nextInt(2) == 1 ? offsetDegree : -offsetDegree;
        canvas.save();
        canvas.rotate(offsetDegree, mWidth / 2, mHeight / 2);
        mTextPaint.setARGB(255, mRandom.nextInt(200) + 20,
                mRandom.nextInt(200) + 20, mRandom.nextInt(200) + 20);
        canvas.drawText(String.valueOf(mCodeString.charAt(i - 1)),
                (i - 1) * charLength * 1.6f + 30, mHeight * 2 / 3f, mTextPaint);
        canvas.restore();
    }

    // 干擾效果一:干擾點
    for (int i = 0; i < mPointNumber; i++) {
        mPointPaint.setARGB(255, mRandom.nextInt(200) + 20,
                mRandom.nextInt(200) + 20, mRandom.nextInt(200) + 20);
        drawPoint(canvas, mPointPaint);
    }

    // 干擾效果二:干擾線
    for (int i = 0; i < mLineNumber; i++) {
        mPathPaint.setARGB(255, mRandom.nextInt(200) + 20,
                mRandom.nextInt(200) + 20, mRandom.nextInt(200) + 20);
        drawLine(canvas, mPathPaint);
    }
    canvas.save();
    return sourceBitmap;
}

三、重寫 onDraw 畫出驗證碼

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    mHeight = getHeight();
    mWidth = getWidth();
    if (bitmap == null) {
        bitmap = generateValidate();
    }
    canvas.drawBitmap(bitmap, 0, 0, mBitmapPaint);
}

四、加上觸控事件,點一下就換一組

@Override
public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            mCodeString = getValidationCode(mCodeCount);
            bitmap = generateValidate();
            invalidate();
            break;
        default:
            break;
    }
    return super.onTouchEvent(event);
}

五、對外提供的公開方法

自訂 View 寫完,記得開幾個方法給外部呼叫,方便做後續的驗證與重送:

/** 比對驗證碼,忽略大小寫 */
public Boolean isEqualsIgnoreCase(String CodeString) {
    return mCodeString.equalsIgnoreCase(CodeString);
}

/** 比對驗證碼,區分大小寫 */
public Boolean isEquals(String CodeString) {
    return mCodeString.equals(CodeString);
}

/** 供外部控制項呼叫,重新整理驗證碼圖片 */
public void refresh() {
    mCodeString = getValidationCode(mCodeCount);
    bitmap = generateValidate();
    invalidate();
}

以上就是一個簡易本機驗證碼自訂 View 的完整流程。有興趣的人可以往下挖看看原始碼:
https://github.com/myloften/VerificationCodeSample

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved