安卓验证码的简单实现

安卓验证码的简单实现

我们经常在登录或者注册的时候要求输入验证码,这里简单介绍一下一种方法
效果如下

这里写图片描述


首先是要获取 随机的四个字母组合,我这里是将26个字母存储到一个数组中,然后随机生成4个下标值,取这四个下标值对应的字母作为验证码。

public class RandomChars {
    char[] chars;

    public RandomChars() {
        chars = new char[26];
        for (int i = 0; i < 26; i++) {
            chars[i] = (char) (i + 65);
        }
    }

    public char[] get4Chars() {
        char[] rlt = new char[4];
        for (int i = 0; i < rlt.length; i++) {
            int randomIndex = (int) (Math.random() * 26);
            rlt[i] = chars[randomIndex];
        }
        return rlt;
    }
}

自定义一个CodeView进行验证码的绘制,主要在onDraw方法中操作,学艺不精,还不能好好在onMeasure中控制大小位置等。

        float unitWidth = (float) getWidth() / (float) chars.length;
        for (int i = 0; i < chars.length; i++) {
            String str = chars[i] + "";
            textPaint.getTextBounds(str, 0, str.length(), mRect);
            resetColor();
            int angel = (int) (Math.random()*(8-(-8)+1)+(-8));
            canvas.rotate(angel);//旋转字母,随机角度
            canvas.drawText(str, i * unitWidth + 5, getHeight() / 2 - mRect.centerY(), textPaint);
            /**
             * 很关键,旋转
             */
            canvas.save();//保存状态
            canvas.restore();//恢复
        }

/**
 * 重新设置随机颜色
 */
    private void resetColor() {
        int r = (int) (Math.random() * 230 - 30);
        int g = (int) (Math.random() * 230 - 30);
        int b = (int) (Math.random() * 230 - 30);
        textPaint.setColor(Color.rgb(r, g, b));
    }

设置该控件并传入四个字符就ok了,验证是否输入正确的时候,考虑到大小写问题,所以将输入的字母全部转换成大写,一般都是不区分大小写。

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String inputStr = input.getText().toString();
                inputStr = inputStr.toUpperCase();
                str = str.toUpperCase();
                if (str.equals(inputStr)) {
                    Toast.makeText(MainActivity.this, "输入正确", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MainActivity.this, "验证码输入错误", Toast.LENGTH_SHORT).show();
                    char[] getchar = randomChars.get4Chars();
                    str = new String(getchar);
                    codeView.setChars(getchar);
                }
            }
        });

感觉还有挺多不足的地方,以后继续改进吧!

猜你喜欢

转载自blog.csdn.net/lizebin_bin/article/details/51035050
今日推荐