編輯:關於 Android 程式設計
接續上一篇,這次要補上中間的關鍵環節——中文驗證碼。先來看最終要達到的效果:

把需求拆開來看,這是一張由四個隨機中文字組成的驗證碼:文字內容隨機、顏色隨機、每個字帶有不同程度的旋轉,周圍再灑上一些干擾元素;點擊「看不清」時整張圖重新生成。逐項對應的實作思路如下:
invalidate() 觸發重繪。依上述分析,自定義一個 CodeView 繼承 ImageView 來承擔繪製工作。先定義可外部配置的自定義屬性:
<!-- attrs.xml -->
<resources>
<!-- 干擾項數量 -->
<attr format="integer" name="disturbSize" />
<!-- 干擾項文字大小 -->
<attr format="dimension" name="disturbTextSize" />
<!-- 干擾項文字顏色 -->
<attr format="color" name="disturbTextColor" />
<!-- 驗證碼文字大小 -->
<attr format="dimension" name="codeTextSize" />
<!-- 驗證碼文字顏色 -->
<attr format="color" name="codeTextColor" />
<!-- 畫布旋轉度數 -->
<attr format="integer" name="rotate" />
<declare-styleable name="CodeView">
<attr name="disturbSize" />
<attr name="disturbTextSize" />
<attr name="disturbTextColor" />
<attr name="codeTextSize" />
<attr name="codeTextColor" />
<attr name="rotate" />
</declare-styleable>
</resources>
對應的成員變數與建構子:
/** 干擾字元池 */
private 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'};
private Paint hzPaint; // 驗證碼畫筆
private Paint dbPaint; // 干擾項畫筆
private int hzColor, dbColor;
private int DEFAULT_DBSIZE; // 干擾項數量,預設 30
private int DEFAULT_DBCOLOR, DEFAULT_HZCOLOR;
private float dbRandomX, dbRandomY;
private List<String> codeList;
private Random random = new Random();
private Rect mBounds;
private int dbTextSize, hzTextSize;
private int rotate; // 旋轉度數,預設 6
public CodeView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CodeView);
DEFAULT_DBSIZE = ta.getInteger(R.styleable.CodeView_disturbSize, 30);
dbTextSize = DisplayUtil.sp2px(context,
ta.getDimensionPixelSize(R.styleable.CodeView_disturbTextSize, 10));
hzTextSize = DisplayUtil.sp2px(context,
ta.getDimensionPixelSize(R.styleable.CodeView_codeTextSize, 20));
DEFAULT_DBCOLOR = ta.getColor(R.styleable.CodeView_disturbTextColor, 0);
DEFAULT_HZCOLOR = ta.getColor(R.styleable.CodeView_codeTextColor, 0);
rotate = ta.getInteger(R.styleable.CodeView_rotate, 6);
init();
}
「隨機生成中文」和「隨機顏色」這兩件事到處都會用到,抽成工具類比較乾淨:
public class Util {
/** 隨機顏色 */
public static int randomColor() {
int red = (int) (Math.random() * 256);
int green = (int) (Math.random() * 256);
int blue = (int) (Math.random() * 256);
return Color.argb(255, red, green, blue);
}
/** 隨機暗色,避免驗證碼太淺看不清 */
public static int randomDarkColor() {
int red = (int) (Math.random() * 100 + 56);
int green = (int) (Math.random() * 100 + 56);
int blue = (int) (Math.random() * 100 + 56);
return Color.argb(255, red, green, blue);
}
/** 取得指定長度的隨機簡體中文 */
public static String getRandomJianHan(int len) {
StringBuilder ret = new StringBuilder();
for (int i = 0; i < len; i++) {
Random random = new Random();
// GBK 編碼下常用漢字分佈在高位 176~214、低位 161~254
int hightPos = 176 + Math.abs(random.nextInt(39));
int lowPos = 161 + Math.abs(random.nextInt(93));
byte[] b = new byte[2];
b[0] = (byte) hightPos;
b[1] = (byte) lowPos;
try {
ret.append(new String(b, "GBk"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return ret.toString();
}
}
這裡提供了亮色與暗色兩套隨機顏色,實務上驗證碼建議用暗色,淺色在亮背景下容易糊成一片。
/** 隨機組出干擾字串 */
private String createDBCode() {
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < DEFAULT_DBSIZE; i++) {
buffer.append(CHARS[random.nextInt(CHARS.length)]);
}
return buffer.toString();
}
/** 隨機干擾項畫筆樣式 */
private void randomDBStyle() {
dbColor = (0 == DEFAULT_DBCOLOR) ? Util.randomDarkColor() : DEFAULT_DBCOLOR;
dbPaint = new Paint();
dbPaint.setColor(dbColor);
dbPaint.setTextSize(dbTextSize);
}
/** 隨機干擾項位置 */
private void randomDBPosition() {
dbRandomX = (float) Math.random() * getWidth();
dbRandomY = (float) Math.random() * getHeight();
}
驗證碼內容不可能寫死,所以對外提供 setCode() 隨時更換;每畫一個字前先 save()、隨機旋轉、畫完再 restore(),避免旋轉互相污染。
/** 對外設置驗證碼文字 */
public void setCode(List<String> codes) {
this.codeList = codes;
invalidate();
}
/** 隨機驗證碼畫筆樣式 */
private void randomHZStyle() {
hzPaint = new Paint();
hzPaint.setColor(hzColor);
hzPaint.setFakeBoldText(random.nextBoolean());
hzPaint.setTextSize(hzTextSize);
hzPaint.getTextBounds("一", 0, "一".length(), mBounds);
}
@Override
protected void onDraw(Canvas canvas) {
// 先畫干擾項
String dbCode = createDBCode();
for (int i = 0; i < dbCode.length(); i++) {
randomDBStyle();
randomDBPosition();
canvas.drawText(dbCode.charAt(i) + "", dbRandomX, dbRandomY, dbPaint);
}
// 再畫驗證文字
if (null != codeList && codeList.size() > 0) {
for (int i = 0; i < codeList.size(); i++) {
randomHZStyle();
canvas.save();
canvas.rotate((int) (Math.floor(Math.random() * rotate + 1)
- Math.floor(Math.random() * rotate * 2 + 1)));
canvas.drawText(codeList.get(i),
mBounds.width() * (i + 1),
getHeight() / 2 + mBounds.height() / 2, hzPaint);
canvas.restore();
}
}
}
這裡只示範了最基礎的畫布旋轉。若要更花俏的變形效果,可以在這段自由擴充;想用特殊字體,也能在建構階段透過 Typeface 載入。
/** 點擊「看不清」時呼叫 */
public void reSet(List<String> codes) {
hzColor = (0 == DEFAULT_HZCOLOR) ? Util.randomDarkColor() : DEFAULT_HZCOLOR;
this.codeList.clear();
this.codeList = codes;
invalidate();
}
CodeView 的 init():
private void init() {
// 驗證碼顏色統一,只需產生一次
hzColor = (0 == DEFAULT_HZCOLOR) ? Util.randomDarkColor() : DEFAULT_HZCOLOR;
mBounds = new Rect();
codeList = new ArrayList<String>();
}
三個建構子依序互相委派(this(context, null) → this(context, attrs, 0)),確保屬性解析只寫一次。
布局文件:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/ll_all"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context="com.example.junweiliu.hanzicode.MainActivity">
<LinearLayout
android:background="@mipmap/hz_nor_ng"
android:layout_width="280dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:orientation="horizontal">
<com.example.junweiliu.hanzicode.CodeView
android:id="@+id/cv_hz"
android:layout_width="120dp"
android:layout_height="40dp" />
<Button
android:id="@+id/btn_reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:background="@null"
android:text="看不清?"
android:textColor="#4791FF"
android:textSize="14sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
MainActivity:
public class MainActivity extends Activity {
private CodeView mCodeView;
private Button mResetBtn;
private List<String> mCorrectList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
initView();
}
/** 產生四個隨機中文字作為正確答案 */
private void initData() {
mCorrectList = new ArrayList<String>();
for (int i = 0; i < 4; i++) {
mCorrectList.add(Util.getRandomJianHan(1));
}
}
private void initView() {
mCodeView = (CodeView) findViewById(R.id.cv_hz);
mCodeView.setCode(mCorrectList);
mResetBtn = (Button) findViewById(R.id.btn_reset);
mResetBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
initData(); // 換一批答案
mCodeView.reSet(mCorrectList); // 重繪驗證碼
}
});
}
}
第一,驗證碼只是「提高自動化作答成本」的手段,不能當成安全邊界;真正的校驗一定要放在伺服器端,且需具備有效期與失敗次數限制,否則前端再花俏也攔不住腳本。
第二,onDraw 中盡量避免 new 物件。繪製頻率高,反覆配置 Paint、Bitmap 會明顯加重 GC 壓力,實務上可將畫筆提到成員變數重用。
第三,Math.random() 在每次呼叫時都會同步一次隨機源,量大時建議改用單一 Random 實例,甚至 ThreadLocalRandom。
Android 自訂相機拍照功能實作:Camera 預覽、自動對焦與存檔
本文示範如何不用系統相機,而是在自己的 Activity 中完成相機預覽與拍照。核心元件是 SurfaceView(負責顯示預覽畫面)與 Camera(負責硬體控制)。
Android PopupWindow 底部彈出與背景漸暗效果
在 Android 中,Dialog、PopupMenu 與 PopupWindow 都能做出彈出式選單。PopupMenu 適合在按鈕附近顯示簡單選單;PopupWin
美團 Android 資源混淆保護實踐全解析
前言 Android 應用的 APK 安全性一直為人詬病。市面上充斥著各種被破解或漢化的應用,破解者只需借助工具就能輕易對 APK 進行反編譯、破解、漢化,進而篡改原有代
Android PopupWindow 使用詳解與 6.0 源碼差異
本文參考〈Android PopupWindow 用法解析〉一文進行學習,透過實例與源碼分析掌握了 PopupWindow 的使用方式。原文最後「補充案例:彈窗不消失,但