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

進階自訂 View:繪製帶干擾線與自訂屬性的驗證碼

編輯:關於 Android 程式設計

先看成品。

這種驗證碼很常見,點一下還會換一組。動手做一遍,就能把自訂 View 的四個標準步驟與自訂屬性一起練熟。

一、自訂 View 的四個步驟

自訂 View 被視為 Android 進階的分水嶺,但流程其實固定:繼承 View、改寫構造方法、必要時改寫 onMeasure 處理測量、改寫 onDraw 完成繪製。真正難的是畫出複雜圖形,那需要一些座標與幾何變換的功底。

其中 onMeasure 並非每次都要改寫,只有當希望控件支援 wrap_content 時才必須處理。因為若版面檔中只寫 wrap_content 而沒有實作測量,系統無從得知你在 onDraw 裡畫了多大的圖形,就會得到 0 尺寸。若控件需要對外開放設定,還要額外定義自訂屬性。

二、繼承 View 與三個構造方法

public class ValidationCode extends View {

    /** 在 java 代碼中創建 view 時調用 */
    public ValidationCode(Context context) {
        this(context, null);
    }

    /** 在 xml 布局中使用但未指定 style 時調用 */
    public ValidationCode(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    /** 在 xml 布局中使用並指定 style 時調用 */
    public ValidationCode(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        getAttrValues(context, attrs);
        init();
    }
}

三個構造方法的呼叫時機如註解所示,慣例是讓參數少的轉呼叫參數多的,把初始化集中在最後一個裡。

初始化工作包含產生驗證碼字串、建立三支畫筆:

/** 初始化一些數據 */
private void init() {
    // 生成隨機數字和字母組合
    mCodeString = getCharAndNumr(mCodeCount);

    // 文字畫筆
    mTextPaint = new Paint();
    mTextPaint.setStrokeWidth(3);
    mTextPaint.setTextSize(mTextSize);

    // 干擾點畫筆
    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);

    // 取得驗證碼字串的顯示寬度
    mTextWidth = mTextPaint.measureText(mCodeString);
}

三、改寫 onMeasure 支援 wrap_content

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int measureWidth = measureWidth(widthMeasureSpec);
    int measureHeight = measureHeight(heightMeasureSpec);
    // 最終會呼叫 setMeasuredDimension 完成測量
    setMeasuredDimension(measureWidth, measureHeight);
}

寬度測量:

private int measureWidth(int widthMeasureSpec) {
    int result = (int) (mTextWidth * 1.8f);
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    if (widthMode == MeasureSpec.EXACTLY) {
        // 精確模式:layout_width 為具體值或 match_parent
        result = widthSize;
    } else if (widthMode == MeasureSpec.AT_MOST) {
        // 最大值模式:layout_width 為 wrap_content
        result = Math.min(result, widthSize);
    }
    return result;
}

高度測量:

private int measureHeight(int heightMeasureSpec) {
    int result = (int) (mTextWidth / 1.6f);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);
    if (heightMode == MeasureSpec.EXACTLY) {
        result = heightSize;
    } else if (heightMode == MeasureSpec.AT_MOST) {
        result = Math.min(result, heightSize);
    }
    return result;
}

這兩個方法幾乎是模板:EXACTLY 代表版面已指定精確尺寸,直接採用;AT_MOST 代表 wrap_content,則取「依內容算出的值」與「可用上限」中的較小者。至于 UNSPECIFIED(多見於 ScrollView 內),可自行決定是否處理。result 的初值本身不需要很精準,只要是一個合理的估算即可。

四、改寫 onDraw 繪製圖形

依需求分三層:驗證碼文字、干擾點、干擾線。後兩者需要座標與路徑,因此先準備資料:

private void initData() {
    // 此時測量已完成,可安全取得寬高
    mHeight = getHeight();
    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);
    }
}

1. 隨機產生驗證碼字串

/** 產生隨機數字與字母組合 */
public static String getCharAndNumr(int length) {
    String val = "";
    Random random = new Random();
    for (int i = 0; i < length; i++) {
        // 決定這一位是字母還是數字
        String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
        if ("char".equalsIgnoreCase(charOrNum)) {
            // 再決定大小寫:65 為 A,97 為 a
            int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
            val += (char) (choice + random.nextInt(26));
        } else if ("num".equalsIgnoreCase(charOrNum)) {
            val += String.valueOf(random.nextInt(10));
        }
    }
    return val;
}

2. 繪製傾斜的文字

Canvas 提供 drawText、drawPosText、drawTextOnPath 幾種繪字方法。drawTextOnPath 能沿路徑繪字、天然產生傾斜,但座標與路徑難以控制。改用 canvas.rotate() 搭配 drawText() 簡單得多:

int length = mCodeString.length();
float charLength = mTextWidth / length;
for (int i = 1; i <= length; i++) {
    int offsetDegree = mRandom.nextInt(15);
    // 隨機決定正轉或反轉
    offsetDegree = mRandom.nextInt(2) == 1 ? offsetDegree : -offsetDegree;

    canvas.save();
    canvas.rotate(offsetDegree, mWidth / 2, mHeight / 2);
    // 隨機顏色,+20 是為了避開過暗的邊界值
    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();
}

關鍵是 save() 與 restore() 成對出現。Canvas 的旋轉會影響後續所有繪製,若不還原,下一個字符會在上一個的基礎上繼續累加旋轉,最後整組文字歪掉。

3. 繪製干擾點與干擾線

// 干擾點
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);
}

五、點擊換一組

@Override
public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            mCodeString = getCharAndNumr(mCodeCount);
            invalidate(); // 觸發重繪
            break;
        default:
            break;
    }
    return super.onTouchEvent(event);
}

六、自訂屬性提升可配置性

先在 attrs.xml 宣告屬性集:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="IndentifyingCode">
        <attr name="codeCount" format="integer|reference"></attr>
        <attr name="textSize" format="dimension"></attr>
    </declare-styleable>
</resources>

attr 的 name 是屬性名,format 是值型別,多種型別以 | 分隔;declare-styleable 的 name 慣例上取控件類名。若屬性已存在於系統(如 layout_width),直接引用即可,不必再指定 format。

在版面檔中要先引入命名空間才能使用:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    xmlns:lt="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.lt.identifyingcode.ValidationCode
        android:id="@+id/validationCode"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        lt:textSize="25sp"
        android:background="@android:color/darker_gray" />
</RelativeLayout>

新版寫法只需 xmlns:lt="https://schemas.android.com/apk/res-auto";舊版則要寫成 xmlns:lt="https://schemas.android.com/apk/res/你的套件名稱"。

在構造方法中把值讀出來:

TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.IndentifyingCode);
mCodeCount = typedArray.getInteger(R.styleable.IndentifyingCode_codeCount, 5);
mTextSize = typedArray.getDimension(R.styleable.IndentifyingCode_textSize,
        typedArray.getDimensionPixelSize(R.styleable.IndentifyingCode_textSize,
                (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20,
                        getResources().getDisplayMetrics())));
// 用完務必回收,與關閉資料庫、檔案串流同理
typedArray.recycle();

屬性命名規則是「styleable 名稱_屬性名稱」,例如 IndentifyingCode_codeCount。讀完呼叫 recycle() 是必要步驟,漏掉會造成資源洩漏。

七、完整程式碼

package com.lt.identifyingcode;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
import java.util.Random;

public class ValidationCode extends View {

    private int mWidth;
    private int mHeight;

    private Paint mTextPaint;   // 文字畫筆
    private Paint mPointPaint;  // 干擾點畫筆
    private Paint mPathPaint;   // 干擾線畫筆

    private ArrayList<PointF> mPoints = new ArrayList<PointF>();
    private ArrayList<Path> mPaths = new ArrayList<Path>();
    private Random mRandom = new Random();

    private String mCodeString;
    private int mCodeCount;
    private float mTextSize;
    private float mTextWidth;

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

    public ValidationCode(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ValidationCode(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        getAttrValues(context, attrs);
        init();
    }

    /** 讀取版面檔中的自訂屬性 */
    private void getAttrValues(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.IndentifyingCode);
        mCodeCount = typedArray.getInteger(R.styleable.IndentifyingCode_codeCount, 5);
        mTextSize = typedArray.getDimension(R.styleable.IndentifyingCode_textSize,
                typedArray.getDimensionPixelSize(R.styleable.IndentifyingCode_textSize,
                        (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20,
                                getResources().getDisplayMetrics())));
        typedArray.recycle();
    }

    private void init() {
        mCodeString = getCharAndNumr(mCodeCount);

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

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

        mTextWidth = mTextPaint.measureText(mCodeString);
    }

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

    @Override
    protected void onDraw(Canvas canvas) {
        initData();

        int length = mCodeString.length();
        float charLength = mTextWidth / length;
        for (int i = 1; i <= length; i++) {
            int offsetDegree = mRandom.nextInt(15);
            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 (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() {
        mHeight = getHeight();
        mWidth = getWidth();

        mPoints.clear();
        for (int i = 0; i < 150; i++) {
            mPoints.add(new PointF(mRandom.nextInt(mWidth) + 10, mRandom.nextInt(mHeight) + 10));
        }

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

    public static String getCharAndNumr(int length) {
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            if ("char".equalsIgnoreCase(charOrNum)) {
                int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (choice + random.nextInt(26));
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

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

    private int measureWidth(int widthMeasureSpec) {
        int result = (int) (mTextWidth * 1.8f);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        if (widthMode == MeasureSpec.EXACTLY) {
            result = widthSize;
        } else if (widthMode == MeasureSpec.AT_MOST) {
            result = Math.min(result, widthSize);
        }
        return result;
    }

    private int measureHeight(int heightMeasureSpec) {
        int result = (int) (mTextWidth / 1.6f);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        if (heightMode == MeasureSpec.EXACTLY) {
            result = heightSize;
        } else if (heightMode == MeasureSpec.AT_MOST) {
            result = Math.min(result, heightSize);
        }
        return result;
    }

    /** 供外部比對用的驗證碼字串 */
    public String getCodeString() {
        return mCodeString;
    }
}

小結:這個題目表面是自訂 View,實質是 Canvas 繪圖練習,真正的難點在座標計算。以上示範了構造、測量、繪製、事件與自訂屬性五個環節,讀者可以試著調整文字傾斜角度範圍、干擾線數量或改用 drawTextOnPath,觀察視覺效果的變化。另外提醒兩點:onDraw 中每次重繪都重新產生干擾點與路徑會造成不必要的垃圾物件,實務上應在初始化或換碼時才產生一次;而驗證碼若只用於展示與娛樂尚可,真要當作安全防線,比對邏輯必須放在伺服器端。

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