安卓生成验证码

注:只有实现验证码的自定义类,以及MainActivity中的基本使用

声明:这是根据明日科技安卓实例讲解所写的代码
自定义生成验证码的类:

public class Code {
    //验证码内容
    private static final char[] CHARS = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm',
            'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
            'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
    };

    //验证码的默认宽高
    private static final int DEFAULT_WIDTH = 100, DEFAULT_HEIGHT = 40;
    private int width = DEFAULT_WIDTH, height = DEFAULT_HEIGHT;
    //验证码默认随机数的个数
    private static final int DEFAULT_CODE_LENGTH = 4;
    //默认字体大小
    private static final int DEFAULT_FONT_SIZE = 25;
    //默认线条的条数
    private static final int DEFAULT_LINE_NUMBER = 5;
    //padding值
    private int padding_left, padding_top;

    //保存最终生成的验证码的字符串
    private String code;
    //用于生成随机数的Random对象
    private Random random = new Random();


    private static Code bmpCode;

    public static Code getInstance() {
        if (bmpCode == null)
            bmpCode = new Code();
        return bmpCode;
    }

    /**
     * 用于生成验证码图片
     */
    public Bitmap createBitmap() {

        padding_left = 0;
        //绘值位图
        Bitmap bp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        //创建画板
        Canvas c = new Canvas(bp);
        //绘制新的验证码
        code = createCode();
        //设置背景色
        c.drawColor(Color.WHITE);
        //创建画笔
        Paint paint = new Paint();
        //抗锯齿
        paint.setAntiAlias(true);
        //设置字号
        paint.setTextSize(DEFAULT_FONT_SIZE);

        //画验证码
        for (int i = 0; i < code.length(); i++) {
            randomTextStyle(paint);
            randomPadding();
            //绘制显示文字
            c.drawText(code.charAt(i) + "", padding_left, padding_top, paint);
        }

        //绘制干扰线
        for (int i = 0; i < DEFAULT_LINE_NUMBER; i++) {
            //绘制线条
            drawLine(c, paint);
        }
        /*c.save(Canvas.ALL_SAVE_FLAG);//保存
        c.restore();*/
      /*  c.save();
        c.restore();*/
        return bp;
    }

    /**
     * 绘制干扰线
     */
    private void drawLine(Canvas canvas, Paint paint) {
        int color = randomColor();
        //位置
        int startX = random.nextInt(width);
        int startY = random.nextInt(height);
        int stopX = random.nextInt(width);
        int stopY = random.nextInt(height);
        paint.setStrokeWidth(1);   //线条宽度
        paint.setColor(color);
        //绘制线
        canvas.drawLine(startX, startY, stopX, stopY, paint);
    }

    /**
     * 生成字符串的验证码
     */
    private String createCode() {
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < DEFAULT_CODE_LENGTH; i++) {
            buffer.append(CHARS[random.nextInt(CHARS.length)]);
        }
        return buffer.toString();
    }


    /**
     * 生成随机颜色值
     */
    private int randomColor() {
        int red = random.nextInt(256);
        int green = random.nextInt(256);
        int blue = random.nextInt(256);
        return Color.rgb(red, green, blue);
    }

    /**
     * 随机生成文字样式,颜色,粗细,倾斜度
     */
    private void randomTextStyle(Paint paint) {
        int color = randomColor();
        paint.setColor(color);
        //true为粗体,false为非粗体
        paint.setFakeBoldText(random.nextBoolean());
        //float类型参数,设置文字倾斜度,负值左斜,正值右斜
        float skewX = random.nextInt(11) / 10;
        skewX = random.nextBoolean() ? skewX : -skewX;
        paint.setTextSkewX(skewX);
        //true为下划线,false为非下划线
        //paint.setUnderlineText(random.nextBoolean());
        //true为删除线,false为非删除线
        //paint.setStrikeThruText(random.nextBoolean());
    }

    /**
     * 随机生成文字间padding值
     */
    private void randomPadding() {
        padding_left += 10 + random.nextInt(15);      //+=:验证码之间的间隔
        padding_top = 15 + random.nextInt(20);
    }

    /**
     * 得到验证码
     */
    public String getCode() {
        return code;
    }
}

MainActivity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView iv_showCode;
    private String code;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //初始化显示验证码控件
        iv_showCode = (ImageView) findViewById(R.id.showCode);
        //将验证码用图片的形式显示出来
        iv_showCode.setImageBitmap(Code.getInstance().createBitmap());
        //获取验证码值
        code = Code.getInstance().getCode().toLowerCase();
        //验证码添加点击事件
        iv_showCode.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        //判断view
        switch (v.getId()) {
            //验证码点击事件
            case R.id.showCode:
                //设置新的验证码
                iv_showCode.setImageBitmap(Code.getInstance().createBitmap());
                //获取验证码值
                code = Code.getInstance().getCode().toLowerCase();
                Log.v("realCode---------->",code);
                break;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无知的小菜鸡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值