溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

android 驗(yàn)證碼 (canvas)

發(fā)布時(shí)間:2020-07-16 15:52:54 來源:網(wǎng)絡(luò) 閱讀:462 作者:hlp666666 欄目:移動(dòng)開發(fā)
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("驗(yàn)證碼:");
    EditText mInCode = new EditText(this);
    vc.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            v.postInvalidate();//重新調(diào)用VerifyCodeView的構(gòu)造方法,更新驗(yàn)證碼
            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];//定義驗(yàn)證碼的長(zhǎng)度
}

public VerifyCodeView(Context context, int codeSize) {
    super(context);
    vcode = new Character[codeSize];//定義驗(yàn)證碼的長(zhǎng)度
}


@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問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI