温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

android 验证码 (canvas)

发布时间:2020-07-16 15:52:54 来源:网络 阅读:451 作者:hlp666666 栏目:移动开发
activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LinearLayout linearLayout = new LinearLayout(this);
    VerifyCodeView vc = new VerifyCodeView(this,6);
    TextView textView = new TextView(this);
    textView.setText("验证码:");
    EditText mInCode = new EditText(this);
    vc.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            v.postInvalidate();//重新调用VerifyCodeView的构造方法,更新验证码
            Toast.makeText(getApplicationContext(),"updat code",Toast.LENGTH_LONG).show();
        }
    });
    linearLayout.addView(textView);
    linearLayout.addView(mInCode);
    linearLayout.addView(vc);
    setContentView(linearLayout);
}

view:

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

public VerifyCodeView(Context context) {
    super(context);
    vcode = new Character[4];//定义验证码的长度
}

public VerifyCodeView(Context context, int codeSize) {
    super(context);
    vcode = new Character[codeSize];//定义验证码的长度
}


@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    vcode = getCodes(codes);
    Paint pen = new Paint();
    pen.setColor(Color.WHITE);
    int mwidth = getWidth();
    canvas.drawRect(mwidth*2/3,10.0f,mwidth-20,100.0f,pen);
    Random r = new Random(100);
    int padding = 1;
    for (int i = 0; i < vcode.length; i++) {
        pen.setColor(Color.rgb(r.nextInt(),r.nextInt(),r.nextInt()));
        pen.setTextSize(60);
        //canvas.drawText(new char[]{'a','c','b','d','1','2','e'},0,7,mwidth*2/3+10,70.0f,pen);
        //String text = "h"+r.nextInt()+"e"+r.nextInt()+"l";
        canvas.drawText(vcode[i].toString(),mwidth*2/3+padding,70.0f,pen);
        padding = padding + 35;
    }
}

public Character[] getCodes(Character[] codes){
    Random rd = new Random();
    for (int i = 0; i < vcode.length; i++) {
        vcode[i] = codes[rd.nextInt(36)];
    }
    return vcode;
}
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI