Android自定义验证码组件

1.声明验证码所需要的属性:

<declare-styleable name="VerifyCodeView">
        <attr name="verifyCodeDimension" format="dimension" />//验证码文字大小
        <attr name="verifyCodeColor" format="color" />//验证码文本颜色
        <attr name="verifyCodeDrawable" format="color|reference" />//验证码背景图
    </declare-styleable>

2.定义验证码类(关键代码处都有注释):

package com.view;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.timeline.R;

import java.util.Random;

/**
 * 
 */
public class VerifyCodeView extends View{

    private final static String TAG = "VerifyCodeView";

    private String mVerifyCodeText;//验证码上的文字
    private Drawable mVerifyCodeBg;//背景图片
    private int mVerifyCodeColor = Color.RED;//默认颜色
    private float mVerifyCodeDimension = 50;//默认字体大小

    private TextPaint mTextPaint;//文本绘制paint
    private float mTextWidth;//文本宽度
    private float mTextHeight;//文本高度

    public VerifyCodeView(Context context) {
        super(context);
        init(null,0);
    }

    public VerifyCodeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs,0);
    }

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

    private void init(AttributeSet attrs, int defStyleAttr){
        //获取属性数组
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.VerifyCodeView,defStyleAttr,0);
        if (a.hasValue(R.styleable.VerifyCodeView_verifyCodeColor)){
            //获取自定义的颜色
            mVerifyCodeColor = a.getColor(R.styleable.VerifyCodeView_verifyCodeColor,Color.RED);
        }
        if (a.hasValue(R.styleable.VerifyCodeView_verifyCodeDimension)){
            //获取自定义的文字大小
            mVerifyCodeDimension = a.getColor(R.styleable.VerifyCodeView_verifyCodeDimension,0);
        }
        if (a.hasValue(R.styleable.VerifyCodeView_verifyCodeDrawable)){
            //获取自定义的背景图
            mVerifyCodeBg = a.getDrawable(R.styleable.VerifyCodeView_verifyCodeDrawable);
        }
        //回调方法,刷新验证文本
        this.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mVerifyCodeText = createVerifyCodeText();
                postInvalidate();
            }
        });
        a.recycle();
        mTextPaint = new TextPaint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextAlign(Paint.Align.CENTER);
        mTextPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
        mVerifyCodeText = createVerifyCodeText();
        invalidateTextPaint();
    }

    //生成验证码文本
    private String createVerifyCodeText(){
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i=0; i<4; i++){
            int r = random.nextInt(10);
            sb.append(r);
        }
        return sb.toString();
    }

    //初始化属性
    private void invalidateTextPaint(){
        mTextPaint.setColor(mVerifyCodeColor);
        mTextPaint.setTextSize(mVerifyCodeDimension);
        mTextWidth = mTextPaint.measureText(mVerifyCodeText);
        Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics();
        mTextHeight = fontMetrics.bottom;
    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int paddingLeft = getPaddingLeft();
        int paddingRight = getPaddingRight();
        int paddingTop = getPaddingTop();
        int paddingBottom = getPaddingBottom();
        int contentWidth = getWidth() - paddingLeft - paddingRight;
        int contentHeight = getHeight() - paddingBottom - paddingTop;
        Log.d(TAG, "mVerifyCodeText:" + mVerifyCodeText);
        if (mVerifyCodeBg == null){
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
                getContext().getResources().getDrawable(R.mipmap.verify_bg, null);
            }else {
                mVerifyCodeBg = getContext().getDrawable(R.mipmap.verify_bg);
            }
        }
        //绘制背景图
        mVerifyCodeBg.setBounds(paddingLeft, paddingTop, paddingLeft + contentWidth, paddingTop + contentHeight);
        mVerifyCodeBg.draw(canvas);
        Rect rect = mVerifyCodeBg.getBounds();
        Log.d(TAG,paddingLeft+","+getLeft()+","+paddingTop);
        //绘制文本
        canvas.drawText(mVerifyCodeText, getLeft() + (rect.width()/2 - mTextWidth/2),
                paddingTop + rect.height()/2 + mTextHeight, mTextPaint);
    }

    //获取验证码文本
    public String getmVerifyCodeText(){
        return mVerifyCodeText;
    }
    //设置背景图
    public void setmVerifyCodeBg(Drawable mVerifyCodeBg) {
        this.mVerifyCodeBg = mVerifyCodeBg;
        invalidateTextPaint();
    }
   //设置文本颜色
    public void setmVerifyCodeColor(int mVerifyCodeColor) {
        this.mVerifyCodeColor = mVerifyCodeColor;
        invalidateTextPaint();
    }
   //设置文本字体大小
    public void setmVerifyCodeDimenssion(float mVerifyCodeDimenssion) {
        this.mVerifyCodeDimension = mVerifyCodeDimenssion;
        invalidateTextPaint();
    }

}

3.使用验证码控件:

    <com.view.VerifyCodeView
        android:id="@+id/verify_code"
        android:layout_width="80dp"
        android:layout_height="40dp"
        />
    注:当需要使用自定义的属性时需要在布局文件开始处的scheme文件中加上:
    xmlns:app="http://schemas.android.com/apk/res-auto",然后就可以使用
    app:verifyCodeColor="xxx"等三个自定义的属性。

4.查看效果:
验证码
点击组件是可以刷新图片上的验证码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值