Android验证码简单设计

来源:互联网 发布:收银软件论坛 编辑:程序博客网 时间:2024/06/06 09:47

看到网站上有验证码,突然就想到在android上自己写一个验证码的demo。基本原理就是自定义一个控件,然后在控件上写上数字以及一个噪音字符和线条,结果比较简单,但是比较有代表性,大家可以根据自己的项目进行自己一改变。在下面的内容中,我将先把自己的代码贴出来,然后解释自己的代码。
1、自定义一个view
1.1、 自定义declare-styleable
在res/values文件夹下新建文件random_textview.xml

<?xml version="1.0" encoding="utf-8"?>    <resources>        <attr name="textColor" format="color"/>        <attr name="textText" format="string"/>        <attr name="textSize" format="dimension" />          <declare-styleable name="random_view">              <attr name="textText" />              <attr name="textColor" />              <attr name="textSize" />          </declare-styleable>    </resources>    

1.2、自定义RandomView

public class RandomView extends View{     private String text;     private int textSize = 0;     private int textColor = 0;     private Rect mBound;     private Paint mPaint;     private int lineNum = 1;//干扰线的数目     private float [] points;     public RandomView(Context context) {          this(context,null);           }         public RandomView(Context context, AttributeSet attrs) {             this(context,attrs,0);        }         public RandomView(Context context, AttributeSet attrs, int defStyle) {             super(context, attrs, defStyle);            TypedArray a = context.getTheme().obtainStyledAttributes(attrs,R.styleable.random_view, defStyle, 0);             int index = a.getIndexCount();            for(int i = 0 ; i < index ; i++)            {                int attr = a.getIndex(i);                switch(attr)                {                case R.styleable.random_view_textColor:                    textColor = a.getColor(attr, Color.BLACK);                    break;                case R.styleable.random_view_textSize:                    textSize = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(                            TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));                    break;                case R.styleable.random_view_textText:                    text = a.getString(attr);                    break;                }            }            a.recycle();            mBound = new Rect();            mPaint = new Paint();            mPaint.setTextSize(textSize);            mPaint.getTextBounds(text, 0, text.length(), mBound);            this.setOnClickListener(new OnClickListener() {                @Override                public void onClick(View v) {                    // TODO Auto-generated method stub                    text = randomStr();                    postInvalidate();                }            });        }         private void randomPoint()        {            Random random = new Random();            points = new float[lineNum * 2];            for(int i = 0 ; i < lineNum  ; i++)            {                points[i] = random.nextFloat() * getWidth();                points[i+1] = random.nextFloat() * getHeight();            }        }        private String randomStr()        {            Random random = new Random();            StringBuilder sb = new StringBuilder();            sb.append(random.nextInt(10))              .append(random.nextInt(10))              .append(random.nextInt(10))              .append(random.nextInt(10));            return sb.toString();        }        @Override        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {            // TODO Auto-generated method stub            //super.onMeasure(widthMeasureSpec, heightMeasureSpec);            int widthMode = MeasureSpec.getMode(widthMeasureSpec);            int widthSize = MeasureSpec.getSize(widthMeasureSpec);            int heightMode = MeasureSpec.getMode(heightMeasureSpec);            int heightSize = MeasureSpec.getSize(heightMeasureSpec);            int width = 0;            int height = 0;            mPaint.setTextSize(textSize);              mPaint.getTextBounds(text, 0, text.length(), mBound);              if(widthMode == MeasureSpec.EXACTLY)            {                width = widthSize + getPaddingLeft() + getPaddingRight();            }            else            {                mPaint.setTextSize(textSize);                  mPaint.getTextBounds(text, 0, text.length(), mBound);                 float textWidth = mBound.width();                width = (int)(getPaddingLeft() + textWidth + getPaddingRight());            }            if(heightMode == MeasureSpec.EXACTLY)            {                height = heightSize + getPaddingBottom() + getPaddingTop();            }            else            {                mPaint.setTextSize(textSize);                  mPaint.getTextBounds(text, 0, text.length(), mBound);                 float textHeight = mBound.height();                height = (int)(getPaddingTop() + textHeight + getPaddingBottom());            }            setMeasuredDimension(width, height);        }        @Override        protected void onDraw(Canvas canvas) {            // TODO Auto-generated method stub             super.onDraw(canvas);             mPaint.setColor(Color.YELLOW);               canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint);               mPaint.setColor(textColor);               canvas.drawText(text, getWidth() / 2 - mBound.width() / 2, getHeight() / 2 + mBound.height() / 2, mPaint);               randomPoint();             //化10条随机线             mPaint.setColor(Color.BLACK);             mPaint.setAlpha(100);             mPaint.setStrokeWidth(20);             canvas.drawLines(points, mPaint);        }}

2、代码解释

private void randomPoint(){    Random random = new Random();    points = new float[lineNum * 2];    for(int i = 0 ; i < lineNum  ; i++)    `这里写代码片`{    points[i] = random.nextFloat() * getWidth();    points[i+1] = random.nextFloat() * getHeight();}

随机生成lineNum个点

private String randomStr()  {    Random random = new Random();    StringBuilder sb = new StringBuilder();    sb.append(random.nextInt(10))      .append(random.nextInt(10))      .append(random.nextInt(10))      .append(random.nextInt(10));    return sb.toString();   }

随机生成4为随机码

3、实际使用
新建MainActivity,布局文件如下

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    xmlns:custom="http://schemas.android.com/apk/res/com.example.selfview"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.example.selfview.MainActivity" >    <com.myviews.RandomView        android:layout_centerInParent="true"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        custom:textText="1234"         custom:textColor="@android:color/holo_red_dark"        custom:textSize="40sp"/></RelativeLayout>运行程序后点击就可以看到验证码效果。结果比较简单,但是拿来修改后依然可以完成自己的效果。
0 0