編輯:關於 Android 程式設計

整個做法其實很直觀:先準備一個字符池,從中隨機挑出指定數量的字符組成驗證碼;接著用畫筆(Paint)把它們逐個畫到自訂的 Bitmap 畫布上;最後再隨機畫上幾條干擾線。真正讓驗證碼「看起來不容易被機器辨識」的關鍵,在於所有繪製參數都帶有隨機性——顏色、粗細、傾斜角度、字元間距、線條走向,全部由亂數決定。
準備一組數字與大小寫英文字母,作為隨機取字的來源。
/** 所有可用來產生驗證碼的字符 */
private static final char[] CHARS = {
'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'
};
長度由外部傳入的 CODE_LENGTH 決定,逐位隨機抽字並拼接。
/** 依設定長度隨機產生驗證碼字串 */
private String createCode() {
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < CODE_LENGTH; i++) {
buffer.append(CHARS[random.nextInt(CHARS.length)]);
}
return buffer.toString();
}
驗證碼終究是一張圖,所以先建一張 Bitmap,再用它包裝出 Canvas,最後鋪上底色。
Bitmap bitmap = Bitmap.createBitmap(DEFAULT_WIDTH, DEFAULT_HEIGHT, Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); canvas.drawColor(Color.rgb(DEFAULT_COLOR, DEFAULT_COLOR, DEFAULT_COLOR));
Paint paint = new Paint(); paint.setTextSize(FONT_SIZE);
字體樣式是隨機性的重點,粗細與傾斜方向都交由亂數決定:
/** 隨機設定驗證碼字體樣式 */
private void randomTextStyle(Paint paint) {
paint.setColor(randomColor(1));
paint.setFakeBoldText(random.nextBoolean()); // true 粗體,false 非粗體
float skewX = random.nextInt(11) / 10;
skewX = random.nextBoolean() ? skewX : -skewX;
paint.setTextSkewX(skewX); // 負數右斜、正數左斜
}
顏色同樣是隨機的,透過 rate 參數可以整體調暗或調亮:
/** 隨機產生顏色,rate 越大顏色越深 */
private int randomColor(int rate) {
int red = random.nextInt(256) / rate;
int green = random.nextInt(256) / rate;
int blue = random.nextInt(256) / rate;
return Color.rgb(red, green, blue);
}
canvas.drawText() 需要文字、X 座標、Y 座標與畫筆四項參數。文字與畫筆都準備好了,剩下的座標就靠隨機間距來決定。
/** 隨機產生字符間距與基線位置 */
private void randomPadding() {
padding_left += BASE_PADDING_LEFT + random.nextInt(RANGE_PADDING_LEFT);
padding_top = BASE_PADDING_TOP + random.nextInt(RANGE_PADDING_TOP);
}
for (int i = 0; i < code.length(); i++) {
randomTextStyle(paint); // 隨機字體樣式
randomPadding(); // 隨機間距
canvas.drawText(code.charAt(i) + "", padding_left, padding_top, paint);
}
干擾線的起點、終點與顏色全部隨機,線寬固定為 1,避免遮蓋主體文字。
/** 畫干擾線 */
private void drawLine(Canvas canvas, Paint paint) {
int startX = random.nextInt(DEFAULT_WIDTH);
int startY = random.nextInt(DEFAULT_HEIGHT);
int stopX = random.nextInt(DEFAULT_WIDTH);
int stopY = random.nextInt(DEFAULT_HEIGHT);
paint.setStrokeWidth(1);
paint.setColor(randomColor(1));
canvas.drawLine(startX, startY, stopX, stopY, paint);
}
for (int i = 0; i < LINE_NUMBER; i++) {
drawLine(canvas, paint);
}
繪製完成後,另外提供一個方法回傳驗證碼本文,供後端比對。這裡統一轉小寫,實作上就不必再判斷大小寫。
/** 取得驗證碼,用於比對使用者輸入 */
public String getCode() {
return code.toLowerCase();
}
把上面的片段組裝起來,就是一個可直接使用的 VerificationCode 類別。它採單例模式,呼叫時傳入「驗證碼長度」與「干擾線數量」兩個參數即可。
package com.duanlian.verificationcodedemo;
import java.util.Random;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Bitmap.Config;
public class VerificationCode {
private static int CODE_LENGTH; // 驗證碼長度
private static int LINE_NUMBER; // 干擾線數量
private static final int FONT_SIZE = 60;
private static final int BASE_PADDING_LEFT = 20;
private static final int RANGE_PADDING_LEFT = 35;
private static final int BASE_PADDING_TOP = 42;
private static final int RANGE_PADDING_TOP = 15;
private static final int DEFAULT_WIDTH = 300; // 驗證碼過多時需加大
private static final int DEFAULT_HEIGHT = 70;
private final int DEFAULT_COLOR = 0xdf;
private String code;
private int padding_left, padding_top;
private Random random = new Random();
private static final char[] CHARS = { /* 0-9 a-z A-Z */ };
private static VerificationCode bpUtil;
private VerificationCode() { }
/** 傳入驗證碼長度與干擾線數量取得實例 */
public static VerificationCode getInstance(int codeLen, int lineNum) {
VerificationCode.CODE_LENGTH = codeLen;
VerificationCode.LINE_NUMBER = lineNum;
if (bpUtil == null) bpUtil = new VerificationCode();
return bpUtil;
}
public Bitmap getBitmap() {
return createBitmap();
}
private Bitmap createBitmap() {
padding_left = 0;
Bitmap bitmap = Bitmap.createBitmap(DEFAULT_WIDTH, DEFAULT_HEIGHT, Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.rgb(DEFAULT_COLOR, DEFAULT_COLOR, DEFAULT_COLOR));
code = createCode();
Paint paint = new Paint();
paint.setTextSize(FONT_SIZE);
for (int i = 0; i < code.length(); i++) {
randomTextStyle(paint);
randomPadding();
canvas.drawText(code.charAt(i) + "", padding_left, padding_top, paint);
}
for (int i = 0; i < LINE_NUMBER; i++) {
drawLine(canvas, paint);
}
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
return bitmap;
}
public String getCode() {
return code.toLowerCase();
}
private String createCode() {
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < CODE_LENGTH; i++) {
buffer.append(CHARS[random.nextInt(CHARS.length)]);
}
return buffer.toString();
}
private void drawLine(Canvas canvas, Paint paint) {
int startX = random.nextInt(DEFAULT_WIDTH);
int startY = random.nextInt(DEFAULT_HEIGHT);
int stopX = random.nextInt(DEFAULT_WIDTH);
int stopY = random.nextInt(DEFAULT_HEIGHT);
paint.setStrokeWidth(1);
paint.setColor(randomColor(1));
canvas.drawLine(startX, startY, stopX, stopY, paint);
}
private int randomColor(int rate) {
return Color.rgb(random.nextInt(256) / rate,
random.nextInt(256) / rate,
random.nextInt(256) / rate);
}
private void randomTextStyle(Paint paint) {
paint.setColor(randomColor(1));
paint.setFakeBoldText(random.nextBoolean());
float skewX = random.nextInt(11) / 10;
paint.setTextSkewX(random.nextBoolean() ? skewX : -skewX);
}
private void randomPadding() {
padding_left += BASE_PADDING_LEFT + random.nextInt(RANGE_PADDING_LEFT);
padding_top = BASE_PADDING_TOP + random.nextInt(RANGE_PADDING_TOP);
}
}
畫面很單純:一張驗證碼圖片、一個輸入框、一顆驗證按鈕。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="驗證碼"
android:textSize="25sp" />
<ImageView
android:id="@+id/image"
android:layout_width="0dp"
android:layout_height="80dp"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="請輸入驗證碼" />
<EditText
android:id="@+id/edittext"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="virification"
android:text="驗證"
android:textSize="30sp" />
</LinearLayout>
Activity 這邊要處理三件事:產生驗證碼並顯示、點擊圖片時刷新、按下驗證鈕時比對結果。值得注意的是,每次刷新後都必須同步更新暫存的驗證碼字串,否則比對的永遠是舊答案。
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private EditText editText;
private VerificationCode code;
private String verificationCode;
private String inputCode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
imageView = (ImageView) findViewById(R.id.image);
editText = (EditText) findViewById(R.id.edittext);
// 參數一:驗證碼字數;參數二:干擾線條數
code = VerificationCode.getInstance(5, 4);
imageView.setImageBitmap(code.getBitmap());
verificationCode = code.getCode();
// 點擊圖片刷新驗證碼
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
imageView.setImageBitmap(code.getBitmap());
verificationCode = code.getCode();
}
});
}
/** 驗證按鈕 */
public void virification(View view) {
inputCode = editText.getText().toString().trim();
if (TextUtils.isEmpty(inputCode)) {
Toast.makeText(MainActivity.this, "請輸入驗證碼", Toast.LENGTH_SHORT).show();
} else if (verificationCode.equals(inputCode)) {
Toast.makeText(MainActivity.this, "驗證成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "您輸入的驗證碼有誤", Toast.LENGTH_SHORT).show();
}
}
}
這套做法的好處是完全不依賴第三方套件,邏輯透明、易於客製。若要真正用於線上服務,建議把驗證碼的產生與比對都放到伺服器端,並加上有效期與一次性使用限制,避免只靠前端攔截。
Android 模擬器無法輸入中文?AVD 中文輸入法設定教學
在 Android 開發與測試過程中,Eclipse、Android Studio 內建模擬器,或 Genymotion 這類第三方模擬器,常被用來快速驗證應用功能。然而
Android 基礎之 Fragment 與 Activity 互動詳解
今天繼續說明 Fragment 元件的特性,重點在於它與 Activity 的互動以及生命週期的關聯。前面提過 Fragment 依賴於 Activity,生命週期也與
Android 學習筆記:RecyclerView 入門實作
RecyclerView 是 android-support-v7 在 21 版時新增的 Widget,官方定位為 ListView 的升級版本,在效能與靈活度上都有明顯
簡析 Android 五大布局與使用情境
Android 介面由布局與元件共同組成。布局決定元件排列,元件負責顯示內容與互動。早期常提到的五大布局包括 LinearLayout、FrameLayout、Relat