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

自定義 View 入門:實作隨機驗證碼控制項

編輯:關於 Android 程式設計

自定義 View 是 Android 開發中相當重要的技能。本文以「產生隨機驗證碼」這個簡單題目作為入門案例,走完自定義 View 的完整流程。

自定義 View 的四個步驟

1. 定義自定義屬性
2. 在自定義版面中取得這些屬性
3. 重寫 onMeasure 方法
4. 重寫 onDraw 方法

就照著這個順序一步一步來。

步驟一:宣告自定義屬性

在 values 目錄下建立 attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="textColor" format="color"/>
    <attr name="textContent" format="string"/>
    <attr name="textSize" format="dimension"/>

    <declare-styleable name="VerificationCodeView">
        <attr name="textContent" />
        <attr name="textColor" />
        <attr name="textSize" />
    </declare-styleable>
</resources>

這裡定義了三個屬性:文字內容、文字顏色、文字大小。

步驟二:建立自定義類別

public class VerificationCodeView extends View {

    /** 文字內容 */
    private String mTitleText;
    /** 文字顏色 */
    private int mTextColor;
    /** 文字大小 */
    private int mTextSize;
    /** 繪製時控制文字範圍 */
    private Rect mBound;
    /** 初始化畫筆 */
    private Paint mTextPaint;
    private Paint mPointPaint;
    private Paint mPathPaint;
    /** 干擾點座標集合 */
    private ArrayList<PointF> mPoints = new ArrayList<PointF>();
    /** 貝茲曲線路徑集合 */
    private ArrayList<Path> mPaths = new ArrayList<Path>();

    public VerificationCodeView(Context context) {
        this(context, null);
    }

    public VerificationCodeView(Context context, AttributeSet attributeSet) {
        this(context, attributeSet, 0);
    }

    public VerificationCodeView(Context context, AttributeSet attributeSet, int defStyle) {
        super(context, attributeSet, defStyle);

        TypedArray typedArray = context.getTheme()
                .obtainStyledAttributes(attributeSet, R.styleable.VerificationCodeView, defStyle, 0);
        int size = typedArray.getIndexCount();
        for (int i = 0; i < size; i++) {
            int content = typedArray.getIndex(i);
            switch (content) {
                case R.styleable.VerificationCodeView_textContent:
                    mTitleText = typedArray.getString(content);
                    break;
                case R.styleable.VerificationCodeView_textColor:
                    mTextColor = typedArray.getColor(content, Color.BLACK);
                    break;
                case R.styleable.VerificationCodeView_textSize:
                    // 預設 16sp,TypedValue 也可將 sp 轉為 px
                    mTextSize = typedArray.getDimensionPixelSize(content,
                            (int) TypedValue.applyDimension(
                                    TypedValue.COMPLEX_UNIT_SP, 16,
                                    getResources().getDisplayMetrics()));
                    break;
            }
        }
        typedArray.recycle();

        // 點擊時換一組驗證碼
        this.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mTitleText = randomText();
                postInvalidate();
            }
        });
    }

    /**
     * EXACTLY:明確數值或 MATCH_PARENT
     * AT_MOST:限制在最大值內,通常為 WRAP_CONTENT
     * UNSPECIFIED:子版面想要多大就多大,很少使用
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        if (widthMode != MeasureSpec.EXACTLY) {
            widthSize = (int) (getPaddingLeft() + mBound.width() + getPaddingRight());
        }
        if (heightMode != MeasureSpec.EXACTLY) {
            heightSize = (int) (getPaddingTop() + mBound.height() + getPaddingBottom());
        }
        setMeasuredDimension(widthSize, heightSize);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // 背景填色
        mTextPaint.setColor(Color.YELLOW);
        canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mTextPaint);

        // 文字顏色
        mTextPaint.setColor(mTextColor);

        // 將文字畫在版面正中
        canvas.drawText(mTitleText,
                getWidth() / 2 - mBound.width() / 2,
                getHeight() / 2 + mBound.height() / 2,
                mTextPaint);
    }

    /** 產生隨機的四位數字驗證碼 */
    private String randomText() {
        Random random = new Random();
        Set<Integer> set = new HashSet<Integer>();
        while (set.size() < 4) {
            set.add(random.nextInt(10));
        }
        StringBuffer sb = new StringBuffer();
        for (Integer i : set) {
            sb.append("" + i);
        }
        return sb.toString();
    }
}

這個類別繼承 View,有三個建構子。由於我們需要讀取自定義屬性,一定要走第三個建構子;但系統預設呼叫的是第二個,所以要在前兩個建構子中逐一委派到第三個,確保初始化一定會執行。

特別注意:這裡呼叫的是 this(...) 而非 super(...),兩者意義完全不同。

步驟三:在版面檔中使用

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:verification="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" >
    <com.example.aotuman.verification.view.VerificationCodeView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        verification:textContent="3712"
        verification:textColor="#ff0000"
        verification:textSize="40sp" />
</RelativeLayout>

使用時必須宣告 xmlns:verification="https://schemas.android.com/apk/res-auto",否則找不到自定義屬性。

到這裡就完成了一個最簡單的版本:黃底紅字、點擊換碼。

進階:加上干擾點與干擾線

驗證碼要能防止機器辨識,需要加上噪訊。改寫 onDraw 並補上兩個輔助方法:

@Override
protected void onDraw(Canvas canvas) {
    initData();
    Random mRandom = new Random();

    // 隨機背景色
    mTextPaint.setARGB(255, mRandom.nextInt(200) + 20,
            mRandom.nextInt(200) + 20, mRandom.nextInt(200) + 20);
    canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mTextPaint);

    // 隨機文字色
    mTextPaint.setARGB(255, mRandom.nextInt(200) + 20,
            mRandom.nextInt(200) + 20, mRandom.nextInt(200) + 20);
    canvas.drawText(mTitleText,
            getWidth() / 2 - mBound.width() / 2,
            getHeight() / 2 + mBound.height() / 2,
            mTextPaint);

    // 干擾效果一:干擾點
    for (PointF pointF : mPoints) {
        mPointPaint.setARGB(255, mRandom.nextInt(200) + 20,
                mRandom.nextInt(200) + 20, mRandom.nextInt(200) + 20);
        canvas.drawPoint(pointF.x, pointF.y, mPointPaint);
    }

    // 干擾效果二:干擾線
    for (Path path : mPaths) {
        mPathPaint.setARGB(255, mRandom.nextInt(200) + 20,
                mRandom.nextInt(200) + 20, mRandom.nextInt(200) + 20);
        canvas.drawPath(path, mPathPaint);
    }
}

private void initData() {
    Random mRandom = new Random();
    // 此時已完成測量
    int mHeight = getHeight();
    int mWidth = getWidth();

    mPoints.clear();
    // 產生干擾點座標
    for (int i = 0; i < 150; i++) {
        PointF pointF = new PointF(
                mRandom.nextInt(mWidth) + 10, mRandom.nextInt(mHeight) + 10);
        mPoints.add(pointF);
    }

    mPaths.clear();
    // 產生干擾線座標
    for (int i = 0; i < 2; i++) {
        Path path = new Path();
        int startX = mRandom.nextInt(mWidth / 3) + 10;
        int startY = mRandom.nextInt(mHeight / 3) + 10;
        int endX = mRandom.nextInt(mWidth / 2) + mWidth / 2 - 10;
        int endY = mRandom.nextInt(mHeight / 2) + mHeight / 2 - 10;
        path.moveTo(startX, startY);
        path.quadTo(Math.abs(endX - startX) / 2,
                Math.abs(endY - startY) / 2, endX, endY);
        mPaths.add(path);
    }
}

private void init() {
    // 初始化文字畫筆並取得文字範圍
    mTextPaint = new Paint();
    mTextPaint.setTextSize(mTextSize);
    mBound = new Rect();
    mTextPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound);

    // 初始化干擾點畫筆
    mPointPaint = new Paint();
    mPointPaint.setStrokeWidth(6);
    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);
}

請記得把 init() 的呼叫加進建構子裡,讓畫筆在使用前先完成初始化。

幾個容易忽略的細節

第一,mBound 是在 init() 中依文字內容計算出來的,所以 onMeasure 若被提前呼叫,要留意 mBound 是否已初始化。第二,onDraw 中呼叫 initData() 每次都會重新產生 150 個點與 2 條曲線,物件配置量不小;實務上可考慮在 onSizeChanged 或產生新驗證碼時才重建座標,避免每幀都配置記憶體。第三,用 HashSet 產生四位數可保證不重複,但也因此限制了某些組合不會出現,若需要允許重複數字,改用一般迴圈即可。

完成之後,這個控制項只要複製檔案就能在其他專案重用,擴充性也不錯——例如要改成中英混雜驗證碼,只需替換 randomText() 的取字邏輯。

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