Android自定義View實現(xiàn)隨機(jī)驗證碼
對于android開發(fā)來說自定義View還是一個比較重要的技能,所以在這里寫一篇自定義View入門的文章,也是實現(xiàn)一個相對簡單的隨機(jī)產(chǎn)生驗證碼的功能:
自定義View主要也就分為幾步
1.自定義View的屬性
2.在我們的自定義的布局中獲取自定義屬性
3.重寫onMesure方法
4.重寫onDraw方法
好現(xiàn)在我們就一步一步的來,首先創(chuàng)建我們的View屬性
在valuse目錄下創(chuàng)建一個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>
我們總共定義了三個屬性,一個是顏色,內(nèi)容,大小
然后我們?nèi)ソ⑽覀兊淖远x類
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;
/**
* 干擾點坐標(biāo)的集合
*/
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:
// 默認(rèn)設(shè)置為16sp,TypeValue也可以把sp轉(zhuǎn)化為px
mTextSize = typedArray.getDimensionPixelSize(content, (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));
break;
}
}
typedArray.recycle();
//設(shè)置點擊事件變換數(shù)字
this.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mTitleText = randomText();
postInvalidate();
}
});
}
/**
* EXACTLY:一般是設(shè)置了明確的值或者是MATCH_PARENT
* AT_MOST:表示子布局限制在一個最大值內(nèi),一般為WARP_CONTENT
* UNSPECIFIED:表示子布局想要多大就多大,很少使用
*
* @param widthMeasureSpec
* @param heightMeasureSpec
*/
@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);
//用來設(shè)置要畫的布局的大小
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) {
//生成隨機(jī)的背景顏色
mTextPaint.setColor(Color.YELLOW);
canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mTextPaint);
//生成隨機(jī)的文字顏色
mTextPaint.setColor(mTextColor);
//將文字畫在布局的中間
canvas.drawText(mTitleText, getWidth() / 2 - mBound.width() / 2, getHeight() / 2 + mBound.height() / 2, mTextPaint);
}
/**
* 生成隨機(jī)的四位數(shù)字驗證碼
*
* @return
*/
private String randomText() {
Random random = new Random();
Set<Integer> set = new HashSet<Integer>();
while (set.size() < 4) {
int randomInt = random.nextInt(10);
set.add(randomInt);
}
StringBuffer sb = new StringBuffer();
for (Integer i : set) {
sb.append("" + i);
}
return sb.toString();
}
}
以上代碼就是自定義的類,繼承了View他有三個構(gòu)造方法,我們要獲取它的屬性,所以一定要走第三個,但是默認(rèn)是第二個,所以我們要在每一個里面調(diào)用第三個,以確保做了初始化工作 注意調(diào)用的時候用的是this的構(gòu)造方法,而不是super
當(dāng)我們的這個類出來之后,后面的就很簡單了
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:verification="http://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>
在布局里面應(yīng)用它就可以了, xmlns:verification=”http://schemas.android.com/apk/res-auto”是必須要的,要不找不到自定義的屬性。
好了到這為止就實現(xiàn)了最簡單的

接下來我們就是實現(xiàn)繪制一些散點和曲線,修改我們的自定義類的onDraw()方法
@Override
protected void onDraw(Canvas canvas) {
initData();
Random mRandom = new Random();
//生成隨機(jī)的背景顏色
mTextPaint.setARGB(255, mRandom.nextInt(200) + 20, mRandom.nextInt(200) + 20, mRandom.nextInt(200) + 20);
canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mTextPaint);
//生成隨機(jī)的文字顏色
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);
// 產(chǎn)生干擾效果1 -- 干擾點
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);
}
// 產(chǎn)生干擾效果2 -- 干擾線
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();
// 獲取控件的寬和高,此時已經(jīng)測量完成
int mHeight = getHeight();
int mWidth = getWidth();
mPoints.clear();
// 生成干擾點坐標(biāo)
for (int i = 0; i < 150; i++) {
PointF pointF = new PointF(mRandom.nextInt(mWidth) + 10, mRandom.nextInt(mHeight) + 10);
mPoints.add(pointF);
}
mPaths.clear();
// 生成干擾線坐標(biāo)
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();
//獲取到的存在mBound里面
mTextPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound);
// 初始化干擾點畫筆
mPointPaint = new Paint();
mPointPaint.setStrokeWidth(6);
mPointPaint.setStrokeCap(Paint.Cap.ROUND); // 設(shè)置斷點處為圓形
// 初始化干擾線畫筆
mPathPaint = new Paint();
mPathPaint.setStrokeWidth(5);
mPathPaint.setColor(Color.GRAY);
mPathPaint.setStyle(Paint.Style.STROKE); // 設(shè)置畫筆為空心
mPathPaint.setStrokeCap(Paint.Cap.ROUND); // 設(shè)置斷點處為圓形
}
init()方法請自行加在構(gòu)造方法里面
OK到這為止就完成了,以后我們用到只要移植就可以了,怎么樣,也很簡單吧

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android使用webView長按保存下載網(wǎng)絡(luò)圖片
這篇文章主要為大家詳細(xì)介紹了Android使用webView長按保存下載網(wǎng)絡(luò)圖片,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-08-08
Android自定義View實現(xiàn)可以拖拽的GridView
這篇文章主要為大家詳細(xì)介紹了Android自定義View實現(xiàn)可以拖拽的GridView,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-06-06
Android開發(fā)之獲取單選與復(fù)選框的值操作示例
這篇文章主要介紹了Android開發(fā)之獲取單選與復(fù)選框的值操作,結(jié)合實例形式分析了Android針對單選按鈕、復(fù)選框的事件響應(yīng)、數(shù)值獲取等相關(guān)操作技巧,需要的朋友可以參考下2019-04-04
Android?Compose之Animatable動畫停止使用詳解
這篇文章主要為大家介紹了Android?Compose之Animatable動畫停止使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
Android 中通過ViewDragHelper實現(xiàn)ListView的Item的側(cè)拉劃出效果
這篇文章主要介紹了 Android 中通過ViewDragHelper實現(xiàn)ListView的Item的側(cè)拉劃出效果,需要的朋友可以參考下2017-08-08

