安卓图形验证码---防止暴力尝试对软件的冲击

ぃ、小莉子 提交于 2020-04-14 14:23:42

【推荐阅读】微服务还能火多久?>>>

在这里插入图片描述
如图所示:图形验证码防止被大量注册刷爆。

//主体代码
public class VerificationCode {
    private static final char[] CHARS = {

            '0','1','2','3','4','5','6','7','8','9',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
            'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
    };

    private static VerificationCode mCodeUtil;
    private int paddingLeft,paddingTop;
    private StringBuilder stringBuilder=new StringBuilder();
    private Random random=new Random();
    private static final int DEFAULT_CODE_LENGTH=4;//验证码长度
    private static final int DEFAULT_FONT_SIZE =60;//验证码字体大小
    private static final int DEFAULT_LINE_NUMBER =3;//干扰线
    private static final int BASE_PADDING_LEFT = 40; //左边距
    private static final int RANGE_PADDING_LEFT = 30;//左边距范围值
    private static final int BASE_PADDING_TOP = 70;//上边距
    private static final int RANGE_PADDING_TOP = 15;//上边距范围值
    private static final int DEFAULT_WIDTH = 300;//默认宽度.图片的总宽
    private static final int DEFAULT_HEIGHT = 100;//默认高度.图片的总高
    private static final int DEFAULT_COLOR = 0xDF;//默认背景颜色值
    private String code;
    public static VerificationCode getInstence(){
        if (mCodeUtil == null){
            mCodeUtil=new VerificationCode();
        }
        return  mCodeUtil;
    }

    //生成bitmap形式的验证码图片可通过image.setBitmap();获取展示图片
    public Bitmap createBitmap(){
        paddingLeft=0;
        paddingTop=0;

        Bitmap bitmap= Bitmap.createBitmap(DEFAULT_WIDTH,DEFAULT_HEIGHT,Bitmap.Config.ARGB_8888);
        Canvas canvas=new Canvas(bitmap);
        code=createCode();
        canvas.drawColor(Color.rgb(DEFAULT_COLOR,DEFAULT_COLOR,DEFAULT_COLOR));
        Paint paint=new Paint();
        paint.setTextSize(DEFAULT_FONT_SIZE);

        //验证码
        for (int i = 0; i <code.length() ; i++) {
            randomTextStyle(paint);
            randomPadding();
            canvas.drawText(String.valueOf(code.charAt(i)),paddingLeft,paddingTop,paint);
        }
        //干扰线
        for (int j = 0; j <DEFAULT_LINE_NUMBER ; j++) {
            drawLine(canvas,paint);
        }

        canvas.save();
        canvas.restore();
        bitmap =bimapRound(bitmap,200);
        return bitmap;
    }
    public Bitmap bimapRound(Bitmap mBitmap,float index){
        Bitmap bitmap = Bitmap.createBitmap(mBitmap.getWidth(), mBitmap.getHeight(), Bitmap.Config.ARGB_4444);

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setAntiAlias(true);

        //设置矩形大小
        Rect rect = new Rect(0,0,mBitmap.getWidth(),mBitmap.getHeight());
        RectF rectf = new RectF(rect);

        // 相当于清屏
        canvas.drawARGB(0, 0, 0, 0);
        //画圆角
        /***
         * Parameters
         * rectf The rectangular bounds of the roundRect to be drawn
         * rx The x-radius of the oval used to round the corners
         * ry The y-radius of the oval used to round the corners
         * x,y方向上的圆角半径
         * paint The paint used to draw the roundRect
         */
        canvas.drawRoundRect(rectf, index, index, paint);
        // 取两层绘制,显示上层
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

        // 把原生的图片放到这个画布上,使之带有画布的效果
        canvas.drawBitmap(mBitmap, rect, rect, paint);
        return bitmap;

    }

    /**
     * 得到图片验证码字符串信息
     */
    public String getCode(){
        return code;
    }

    //生成干扰线
    private void drawLine(Canvas canvas, Paint paint) {
        int color =randomColor();
        int startX = random.nextInt(DEFAULT_WIDTH);
        int startY = random.nextInt(DEFAULT_HEIGHT);
        int stopX = random.nextInt(DEFAULT_WIDTH);
        int stopY = random.nextInt(DEFAULT_HEIGHT);
        paint.setStrokeWidth(1);
        paint.setColor(color);
        canvas.drawLine(startX, startY, stopX, stopY, paint);
    }


    //随机颜色
    private int randomColor() {
        stringBuilder.delete(0, stringBuilder.length()); //使用之前首先清空内容

        String haxString;
        for (int i = 0; i < 3; i++) {
            haxString = Integer.toHexString(random.nextInt(0xFF));
            if (haxString.length() == 1) {
                haxString = "0" + haxString;
            }

            stringBuilder.append(haxString);
        }

        return Color.parseColor("#" + stringBuilder.toString());
    }

    //随机间距
    private void randomPadding() {
        paddingLeft += BASE_PADDING_LEFT + random.nextInt(RANGE_PADDING_LEFT);
        paddingTop = BASE_PADDING_TOP + random.nextInt(RANGE_PADDING_TOP);
    }

    //随机文本样式
    private void randomTextStyle(Paint paint) {
        int color = randomColor();
        paint.setColor(color);
        paint.setFakeBoldText(random.nextBoolean());  //true为粗体,false为非粗体
        float skewX = random.nextInt(11) / 10;
        skewX = random.nextBoolean() ? skewX : -skewX;
        paint.setTextSkewX(skewX); //float类型参数,负数表示右斜,整数左斜
//        paint.setUnderlineText(true); //true为下划线,false为非下划线
//        paint.setStrikeThruText(true); //true为删除线,false为非删除线
    }


    //生成验证码
    private String createCode() {
        stringBuilder.delete(0,stringBuilder.length());
        for (int i = 0; i <DEFAULT_CODE_LENGTH ; i++) {
            stringBuilder.append(CHARS[random.nextInt(CHARS
                    .length)]);
        }
        return stringBuilder.toString();
    }

//调用代码:建立一个函数在注册界面调用

    private void initView() {
        ivCode=findViewById(R.id.ivCode);
        ivCode.setImageBitmap(VerificationCode.getInstence().createBitmap());//创建绘制图像
        ivCode.setOnClickListener(new View.OnClickListener() {//点击刷新
                                      @Override
                                      public void onClick(View v) {
                                          ivCode.setImageBitmap(VerificationCode.getInstence().createBitmap());
                                      }
                                  }

        );
    }

发布了46 篇原创文章 · 获赞 13 · 访问量 1622
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!