android 本地验证码的一种实现

来源:互联网 发布:手机ocr软件 编辑:程序博客网 时间:2024/05/10 09:49

        今天编写了一个本地验证码的Demo和大家一起分享。

        Demo拥有验证码的基本功能,点击切换图片,随机生成验证码,位置动态变化等,还预留了动态改变字体颜色等接口。下边贴出效果图:

       

        

 

        实现如下:

        首先自定义View实现验证码图片的绘制

       

[java] view plaincopy
  1. package com.jacky.mydraw;  
  2.   
  3. import java.util.Random;  
  4.   
  5. import android.content.Context;  
  6. import android.graphics.Bitmap;  
  7. import android.graphics.Bitmap.Config;  
  8. import android.graphics.Canvas;  
  9. import android.graphics.Color;  
  10. import android.graphics.Matrix;  
  11. import android.graphics.Paint;  
  12. import android.util.AttributeSet;  
  13. import android.view.View;  
  14. /** 
  15.  * 功能:自定义验证码实现类 
  16.  * 博客:http://blog.csdn.net/u010538765/article/ 
  17.  * 时间:2013.8.19 
  18.  * @author Jacky 
  19.  * 
  20.  */  
  21. class CheckView extends View  
  22. {     
  23.     //验证码图片  
  24.     private Bitmap bitmap = null;  
  25.     //随机生成所有的数组  
  26.     final String[] strContent = new String[]{"0","1","2","3","4","5""6""7""8""9"};  
  27.       
  28.     //构造函数  
  29.     public CheckView(Context context, AttributeSet attrs) {  
  30.         super(context, attrs);  
  31.     }  
  32.   
  33.     @Override  
  34.     public void draw(Canvas canvas)  
  35.     {  
  36.         Paint paint = new Paint();  
  37.         if (bitmap != null) {  
  38.             canvas.drawBitmap(bitmap, 00, paint);  
  39.         } else {  
  40.             paint.setColor(Color.GRAY);  
  41.             paint.setTextSize(20);  
  42.             canvas.drawText("点击换一换"1030, paint);  
  43.         }  
  44.         super.draw(canvas);  
  45.     }  
  46.   
  47.     /** 
  48.      * 得到验证码;设置图片 
  49.      * @return 生成的验证码中的数字 
  50.      */  
  51.     public String[] getValidataAndSetImage() {  
  52.         //产生随机数  
  53.         String [] strRes = generageRadom(strContent);  
  54.         //传随机串和随机数  
  55.         bitmap = generateValidate(strContent,strRes);  
  56.         //刷新  
  57.         invalidate();  
  58.           
  59.         return strRes;  
  60.     }  
  61.       
  62.     /** 
  63.      * 绘制验证码并返回 
  64.      * @param strContent 
  65.      * @param strRes 
  66.      * @return 
  67.      */  
  68.     private Bitmap generateValidate(String[] strContent,String [] strRes) {  
  69.         int width = 120,height = 57;  
  70.           
  71.         int isRes = isStrContent(strContent);  
  72.         if (isRes == 0) {  
  73.             return null;  
  74.         }  
  75.           
  76.         //创建图片和画布  
  77.         Bitmap sourceBitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);  
  78.         Canvas canvas = new Canvas(sourceBitmap);  
  79.         canvas.drawColor(Color.YELLOW);  
  80.         Paint numPaint = new Paint();  
  81.         numPaint.setTextSize(40);  
  82.         numPaint.setFakeBoldText(true);  
  83.         numPaint.setColor(Color.BLACK);  
  84.           
  85.         //设置每个字  
  86.         canvas.drawText(strRes[0], 10, height * 3 / 4, numPaint);  
  87.         Matrix mMatrix = new Matrix();  
  88.         mMatrix.setRotate((float)Math.random()*25);  
  89.         canvas.setMatrix(mMatrix);  
  90.           
  91.         canvas.drawText(strRes[1], 40, height * 3 / 4, numPaint);  
  92.         mMatrix.setRotate((float)Math.random()*25);  
  93.         canvas.setMatrix(mMatrix);  
  94.           
  95.         canvas.drawText(strRes[2], 70, height * 3 / 4 - 10, numPaint);  
  96.         mMatrix.setRotate((float)Math.random()*25);  
  97.         canvas.setMatrix(mMatrix);  
  98.           
  99.         canvas.drawText(strRes[3], 100, height * 3 / 4 - 15, numPaint);  
  100.         mMatrix.setRotate((float)Math.random()*25);  
  101.         canvas.setMatrix(mMatrix);  
  102.           
  103.         //设置绘制干扰的画笔  
  104.         Paint interferencePaint = new Paint();  
  105.         interferencePaint.setAntiAlias(true);  
  106.         interferencePaint.setStrokeWidth(4);  
  107.         interferencePaint.setColor(Color.BLACK);  
  108.         interferencePaint.setStyle(Paint.Style.FILL);    //设置paint的style  
  109.           
  110.         //绘制直线  
  111.         int [] line;  
  112.         for(int i = 0; i < 2; i ++)  
  113.             {  
  114.             line = CheckGetUtil.getLine(height, width);  
  115.             canvas.drawLine(line[0], line[1], line[2], line[3],interferencePaint);  
  116.             }  
  117.         // 绘制小圆点  
  118.         int [] point;  
  119.         for(int i = 0; i < 100; i++)   
  120.             {  
  121.             point=CheckGetUtil.getPoint(height, width);  
  122.             canvas.drawCircle(point[0], point[1], 1, interferencePaint);  
  123.             }  
  124.           
  125.         canvas.save();  
  126.         return sourceBitmap;  
  127.     }  
  128.       
  129.     private int isStrContent(String[] strContent) {  
  130.         if (strContent == null || strContent.length <= 0) {  
  131.             return 0;  
  132.         } else {  
  133.             return 1;  
  134.         }  
  135.     }  
  136.       
  137.     /** 
  138.      * 从指定数组中随机取出4个字符(数组) 
  139.      * @param strContent 
  140.      * @return 
  141.      */  
  142.     private String[] generageRadom(String[] strContent){  
  143.         String[] str = new String[4];  
  144.         // 随机串的个数  
  145.         int count = strContent.length;  
  146.         // 生成4个随机数  
  147.         Random random = new Random();  
  148.         int randomResFirst = random.nextInt(count);  
  149.         int randomResSecond = random.nextInt(count);  
  150.         int randomResThird = random.nextInt(count);  
  151.         int randomResFourth = random.nextInt(count);  
  152.           
  153.         str[0] = strContent[randomResFirst].toString().trim();  
  154.         str[1] = strContent[randomResSecond].toString().trim();  
  155.         str[2] = strContent[randomResThird].toString().trim();  
  156.         str[3] = strContent[randomResFourth].toString().trim();  
  157.         return str;  
  158.     }  
  159.       
  160.     /** 
  161.      * 从指定数组中随机取出4个字符(字符串) 
  162.      * @param strContent 
  163.      * @return 
  164.      */  
  165.     private String generageRadomStr(String[] strContent){  
  166.         StringBuilder str = new StringBuilder();  
  167.         // 随机串的个数  
  168.         int count = strContent.length;  
  169.         // 生成4个随机数  
  170.         Random random = new Random();  
  171.         int randomResFirst = random.nextInt(count);  
  172.         int randomResSecond = random.nextInt(count);  
  173.         int randomResThird = random.nextInt(count);  
  174.         int randomResFourth = random.nextInt(count);  
  175.           
  176.         str.append(strContent[randomResFirst].toString().trim());  
  177.         str.append(strContent[randomResSecond].toString().trim());  
  178.         str.append(strContent[randomResThird].toString().trim());  
  179.         str.append(strContent[randomResFourth].toString().trim());  
  180.         return str.toString();  
  181.     }  
  182.   
  183.     /** 
  184.      * 给定范围获得随机颜色,未使用 
  185.      *  
  186.      * @param rc 
  187.      *            0-255 
  188.      * @param gc 
  189.      *            0-255 
  190.      * @param bc 
  191.      *            0-255 
  192.      * @return colorValue 颜色值,使用setColor(colorValue) 
  193.      */  
  194.     public int getRandColor(int rc, int gc, int bc) {  
  195.         Random random = new Random();  
  196.         if (rc > 255)  
  197.             rc = 255;  
  198.         if (gc > 255)  
  199.             gc = 255;  
  200.         if (bc > 255)  
  201.             bc = 255;  
  202.         int r = rc + random.nextInt(rc);  
  203.         int g = gc + random.nextInt(gc);  
  204.         int b = bc + random.nextInt(bc);  
  205.         return Color.rgb(r, g, b);  
  206.     }  
  207. }  

 

         随后在XML文件中添加自定义View:

[html] view plaincopy
  1. <com.jacky.mydraw.CheckView  
  2.             android:id="@+id/checkView"  
  3.             android:layout_width="80sp"  
  4.             android:layout_height="38sp"  
  5.             android:layout_marginLeft="5dp" >  
  6. </com.jacky.mydraw.CheckView>  

 

       编写工具类,随机生成线和点的位置,验证验证码,生成随机数等均可在此类中进行。

 

[java] view plaincopy
  1. package com.jacky.mydraw;  
  2. /** 
  3.  * 功能:验证码相关工具类 
  4.  * 博客:http://blog.csdn.net/u010538765/article/ 
  5.  * 时间:2013.8.19 
  6.  * @author Jacky 
  7.  * */  
  8. public class CheckGetUtil  
  9. {  
  10.     //获得画干扰直线的位置  
  11.     public static int[] getLine(int height, int width)  
  12.     {  
  13.         int [] tempCheckNum = {00 ,000};  
  14.         for(int i = 0; i < 4; i+=2)  
  15.             {  
  16.             tempCheckNum[i] = (int) (Math.random() * width);  
  17.             tempCheckNum[i + 1] = (int) (Math.random() * height);  
  18.             }  
  19.         return tempCheckNum;  
  20.     }  
  21.       
  22.     //获得干扰点的位置  
  23.     public static int[] getPoint(int height, int width)  
  24.     {  
  25.         int [] tempCheckNum = {00000};  
  26.         tempCheckNum[0] = (int) (Math.random() * width);  
  27.         tempCheckNum[1] = (int) (Math.random() * height);  
  28.         return tempCheckNum;  
  29.     }  
  30. }  


         最后,调用实现

 

[java] view plaincopy
  1. package com.jacky.mydraw;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.view.View;  
  6. import android.view.View.OnClickListener;  
  7.   
  8. public class CheckActivity extends Activity   
  9. {  
  10.     private CheckView mMyView = null;  
  11.     private String[] res = new String[4];  //获取每次更新的验证码,可用于判断用户输入是否正确  
  12.     @Override  
  13.     protected void onCreate(Bundle savedInstanceState)  
  14.     {  
  15.         super.onCreate(savedInstanceState);  
  16.         setContentView(R.layout.activity_check);  
  17.           
  18.         mMyView = (CheckView)findViewById(R.id.checkView);  
  19.         //初始化验证码  
  20.         res = mMyView.getValidataAndSetImage();  
  21.         mMyView.setOnClickListener(new OnClickListener() {  
  22.               
  23.             @Override  
  24.             public void onClick(View v) {  
  25.                 //重新初始化验证码  
  26.                 res = mMyView.getValidataAndSetImage();           
  27.             }  
  28.         });  
  29.     }     
  30. }  


        该Demo实现了简单的验证码功能,可以根据需要自行修改。

转自:http://blog.csdn.net/u010538765/article/details/10084951

0 0
原创粉丝点击