簡單實現(xiàn)Android驗證碼
安卓驗證碼的簡單實現(xiàn)
我們經(jīng)常在登錄或者注冊的時候要求輸入驗證碼,這里簡單介紹一下一種方法
效果如下
首先是要獲取 隨機的四個字母組合,我這里是將26個字母存儲到一個數(shù)組中,然后隨機生成4個下標值,取這四個下標值對應(yīng)的字母作為驗證碼。
public class RandomChars { char[] chars; public RandomChars() { chars = new char[26]; for (int i = 0; i < 26; i++) { chars[i] = (char) (i + 65); } } public char[] get4Chars() { char[] rlt = new char[4]; for (int i = 0; i < rlt.length; i++) { int randomIndex = (int) (Math.random() * 26); rlt[i] = chars[randomIndex]; } return rlt; } }
自定義一個CodeView進行驗證碼的繪制,主要在onDraw方法中操作,學(xué)藝不精,還不能好好在onMeasure中控制大小位置等。
float unitWidth = (float) getWidth() / (float) chars.length; for (int i = 0; i < chars.length; i++) { String str = chars[i] + ""; textPaint.getTextBounds(str, 0, str.length(), mRect); resetColor(); int angel = (int) (Math.random()*(8-(-8)+1)+(-8)); canvas.rotate(angel);//旋轉(zhuǎn)字母,隨機角度 canvas.drawText(str, i * unitWidth + 5, getHeight() / 2 - mRect.centerY(), textPaint); /** * 很關(guān)鍵,旋轉(zhuǎn) */ canvas.save();//保存狀態(tài) canvas.restore();//恢復(fù) } /** * 重新設(shè)置隨機顏色 */ private void resetColor() { int r = (int) (Math.random() * 230 - 30); int g = (int) (Math.random() * 230 - 30); int b = (int) (Math.random() * 230 - 30); textPaint.setColor(Color.rgb(r, g, b)); }
設(shè)置該控件并傳入四個字符就ok了,驗證是否輸入正確的時候,考慮到大小寫問題,所以將輸入的字母全部轉(zhuǎn)換成大寫,一般都是不區(qū)分大小寫。
submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String inputStr = input.getText().toString(); inputStr = inputStr.toUpperCase(); str = str.toUpperCase(); if (str.equals(inputStr)) { Toast.makeText(MainActivity.this, "輸入正確", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(MainActivity.this, "驗證碼輸入錯誤", Toast.LENGTH_SHORT).show(); char[] getchar = randomChars.get4Chars(); str = new String(getchar); codeView.setChars(getchar); } } });
感覺還有挺多不足的地方,以后繼續(xù)改進吧!
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Kotlin中l(wèi)et()with()run()apply()also()函數(shù)的使用方法與區(qū)別
在Kotlin中的源碼標準庫(Standard.kt)中提供了一些Kotlin擴展的內(nèi)置函數(shù)可以優(yōu)化kotlin的編碼,今天為大家聊聊let,with,run,apply,also幾個函數(shù)的用法與區(qū)別2018-03-03RxJava+Retrofit實現(xiàn)網(wǎng)絡(luò)請求封裝的方法
Retrofit是當前應(yīng)用非常廣泛的網(wǎng)絡(luò)請求框架,通常結(jié)合RxJava來進行網(wǎng)絡(luò)請求,本文將展示一個采用RxJava+Retrofit的網(wǎng)絡(luò)請求demo,感興趣的可以了解一下2019-04-04