android 验证码 (canvas)
2016-01-27 15:38
337 查看
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; }
相关文章推荐
- 控制输入法软键盘隐藏
- Android框架模式(1)-MVP入门
- Android 手写Binder 教你理解android中的进程间通信
- Android traces.txt只保留最后一次发生ANR时的traces信息,那么以前的traces信息就丢失了么?
- 讨论一个Android 异步开发中容易忽视的bug
- Android之服务
- Android camera2预览界面流程
- Android内存泄漏简介
- 转载Android中全屏或者取消标题栏
- Android:我为何要封装DialogFragment?
- Android之使用 AsyncTask
- Android中滑屏实现----手把手教你如何实现触摸滑屏以及Scroller类详解
- Android之Service与IntentService的比较
- Android之异步消息处理机制
- Android Timer 定时器 与handler的配合
- [Android Pro] 使用apktool工具遇到could not decode arsc file的解决办法
- Android之多线程编程
- 五步搞定Android开发环境部署——非常详细的Android开发环境搭建教程
- android studio---Duplicate files copied in APK META-INF/LICENSE.txt 错误解决
- NotBoringActionBar项目的思路解析