当前位置: 移动技术网 > IT编程>移动开发>Android > Android自定义View实现随机验证码

Android自定义View实现随机验证码

2019年07月24日  | 移动技术网IT编程  | 我要评论

勒布朗詹姆斯十佳球,供销e家休闲农业,消防安全手抄报资料

对于android开发来说自定义view还是一个比较重要的技能,所以在这里写一篇自定义view入门的文章,也是实现一个相对简单的随机产生验证码的功能:
自定义view主要也就分为几步
 1.自定义view的属性
 2.在我们的自定义的布局中获取自定义属性
 3.重写onmesure方法
 4.重写ondraw方法
好现在我们就一步一步的来,首先创建我们的view属性
在valuse目录下创建一个attrs.xml的文件,然后:

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <attr name="textcolor" format="color"/>
 <attr name="textcontent" format="string"/>
 <attr name="textsize" format="dimension"/>

 <declare-styleable name="verificationcodeview">
 <attr name="textcontent" />
 <attr name="textcolor" />
 <attr name="textsize" />
 </declare-styleable>
</resources>

我们总共定义了三个属性,一个是颜色,内容,大小

然后我们去建立我们的自定义类

public class verificationcodeview extends view {
 /**
 * 文本
 */
 private string mtitletext;
 /**
 * 文本的颜色
 */
 private int mtextcolor;
 /**
 * 文本的大小
 */
 private int mtextsize;

 /**
 * 绘制时控制文本绘制的范围
 */
 private rect mbound;
 /**
 * 初始化画笔
 */
 private paint mtextpaint;
 private paint mpointpaint;
 private paint mpathpaint;
 /**
 * 干扰点坐标的集合
 */
 private arraylist<pointf> mpoints = new arraylist<pointf>();
 /**
 * 绘制贝塞尔曲线的路径集合
 */
 private arraylist<path> mpaths = new arraylist<path>();

 public verificationcodeview(context context) {
 this(context, null);
 }

 public verificationcodeview(context context, attributeset attributeset) {
 this(context, attributeset, 0);
 }

 public verificationcodeview(context context, attributeset attributeset, int defstyle) {
 super(context, attributeset, defstyle);
 typedarray typedarray = context.gettheme().obtainstyledattributes(attributeset, r.styleable.verificationcodeview, defstyle, 0);
 int size = typedarray.getindexcount();
 for (int i = 0; i < size; i++) {
  int content = typedarray.getindex(i);
  switch (content) {
  case r.styleable.verificationcodeview_textcontent:
   mtitletext = typedarray.getstring(content);
   break;
  case r.styleable.verificationcodeview_textcolor:
   mtextcolor = typedarray.getcolor(content, color.black);
   break;
  case r.styleable.verificationcodeview_textsize:
   // 默认设置为16sp,typevalue也可以把sp转化为px
   mtextsize = typedarray.getdimensionpixelsize(content, (int) typedvalue.applydimension(
    typedvalue.complex_unit_sp, 16, getresources().getdisplaymetrics()));
   break;
  }
 }
 typedarray.recycle();
 //设置点击事件变换数字
 this.setonclicklistener(new onclicklistener() {
  @override
  public void onclick(view v) {
  mtitletext = randomtext();
  postinvalidate();
  }
 });
 }

 /**
 * exactly:一般是设置了明确的值或者是match_parent
 * at_most:表示子布局限制在一个最大值内,一般为warp_content
 * unspecified:表示子布局想要多大就多大,很少使用
 *
 * @param widthmeasurespec
 * @param heightmeasurespec
 */
 @override
 protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
 super.onmeasure(widthmeasurespec, heightmeasurespec);
 int widthmode = measurespec.getmode(widthmeasurespec);
 int widthsize = measurespec.getsize(widthmeasurespec);
 int heightmode = measurespec.getmode(heightmeasurespec);
 int heightsize = measurespec.getsize(heightmeasurespec);
 //用来设置要画的布局的大小
 if (widthmode != measurespec.exactly) {
  widthsize = (int) (getpaddingleft() + mbound.width() + getpaddingright());
 }

 if (heightmode != measurespec.exactly) {
  heightsize = (int) (getpaddingtop() + mbound.height() + getpaddingbottom());
 }

 setmeasureddimension(widthsize, heightsize);
 }

 @override
 protected void ondraw(canvas canvas) {
 //生成随机的背景颜色
 mtextpaint.setcolor(color.yellow);
 canvas.drawrect(0, 0, getmeasuredwidth(), getmeasuredheight(), mtextpaint);
 //生成随机的文字颜色
 mtextpaint.setcolor(mtextcolor);
 //将文字画在布局的中间
 canvas.drawtext(mtitletext, getwidth() / 2 - mbound.width() / 2, getheight() / 2 + mbound.height() / 2, mtextpaint);
 }
 /**
 * 生成随机的四位数字验证码
 *
 * @return
 */
 private string randomtext() {
 random random = new random();
 set<integer> set = new hashset<integer>();
 while (set.size() < 4) {
  int randomint = random.nextint(10);
  set.add(randomint);
 }
 stringbuffer sb = new stringbuffer();
 for (integer i : set) {
  sb.append("" + i);
 }

 return sb.tostring();
 }
}

以上代码就是自定义的类,继承了view他有三个构造方法,我们要获取它的属性,所以一定要走第三个,但是默认是第二个,所以我们要在每一个里面调用第三个,以确保做了初始化工作 注意调用的时候用的是this的构造方法,而不是super
当我们的这个类出来之后,后面的就很简单了

<?xml version="1.0" encoding="utf-8"?>
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:verification="http://schemas.android.com/apk/res-auto"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:gravity="center"
 >

 <com.example.aotuman.verification.view.verificationcodeview
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:paddingtop="10dp"
 android:paddingbottom="10dp"
 android:paddingleft="10dp"
 android:paddingright="10dp"
 verification:textcontent="3712"
 verification:textcolor="#ff0000"
 verification:textsize="40sp" />
</relativelayout>

在布局里面应用它就可以了, xmlns:verification=”http://schemas.android.com/apk/res-auto”是必须要的,要不找不到自定义的属性。

好了到这为止就实现了最简单的

接下来我们就是实现绘制一些散点和曲线,修改我们的自定义类的ondraw()方法

@override
 protected void ondraw(canvas canvas) {
 initdata();
 random mrandom = new random();
 //生成随机的背景颜色
 mtextpaint.setargb(255, mrandom.nextint(200) + 20, mrandom.nextint(200) + 20, mrandom.nextint(200) + 20);
 canvas.drawrect(0, 0, getmeasuredwidth(), getmeasuredheight(), mtextpaint);
 //生成随机的文字颜色
 mtextpaint.setargb(255, mrandom.nextint(200) + 20, mrandom.nextint(200) + 20, mrandom.nextint(200) + 20);
 //将文字画在布局的中间
 canvas.drawtext(mtitletext, getwidth() / 2 - mbound.width() / 2, getheight() / 2 + mbound.height() / 2, mtextpaint);

 // 产生干扰效果1 -- 干扰点
 for (pointf pointf : mpoints) {
  mpointpaint.setargb(255, mrandom.nextint(200) + 20, mrandom.nextint(200) + 20, mrandom.nextint(200) + 20);
  canvas.drawpoint(pointf.x, pointf.y, mpointpaint);
 }
 // 产生干扰效果2 -- 干扰线
 for (path path : mpaths) {
  mpathpaint.setargb(255, mrandom.nextint(200) + 20, mrandom.nextint(200) + 20, mrandom.nextint(200) + 20);
  canvas.drawpath(path, mpathpaint);
 }

 private void initdata() {
 random mrandom = new random();
 // 获取控件的宽和高,此时已经测量完成
 int mheight = getheight();
 int mwidth = getwidth();
 mpoints.clear();
 // 生成干扰点坐标
 for (int i = 0; i < 150; i++) {
  pointf pointf = new pointf(mrandom.nextint(mwidth) + 10, mrandom.nextint(mheight) + 10);
  mpoints.add(pointf);
 }
 mpaths.clear();
 // 生成干扰线坐标
 for (int i = 0; i < 2; i++) {
  path path = new path();
  int startx = mrandom.nextint(mwidth / 3) + 10;
  int starty = mrandom.nextint(mheight / 3) + 10;
  int endx = mrandom.nextint(mwidth / 2) + mwidth / 2 - 10;
  int endy = mrandom.nextint(mheight / 2) + mheight / 2 - 10;
  path.moveto(startx, starty);
  path.quadto(math.abs(endx - startx) / 2, math.abs(endy - starty) / 2, endx, endy);
  mpaths.add(path);
 }
 }

 private void init() {
 // 初始化文字画笔
 /**
  * 获得绘制文本的宽和高
  */
 mtextpaint = new paint();
 mtextpaint.settextsize(mtextsize);

 mbound = new rect();
 //获取到的存在mbound里面
 mtextpaint.gettextbounds(mtitletext, 0, mtitletext.length(), mbound);
 // 初始化干扰点画笔
 mpointpaint = new paint();
 mpointpaint.setstrokewidth(6);
 mpointpaint.setstrokecap(paint.cap.round); // 设置断点处为圆形
 // 初始化干扰线画笔
 mpathpaint = new paint();
 mpathpaint.setstrokewidth(5);
 mpathpaint.setcolor(color.gray);
 mpathpaint.setstyle(paint.style.stroke); // 设置画笔为空心
 mpathpaint.setstrokecap(paint.cap.round); // 设置断点处为圆形
 }

init()方法请自行加在构造方法里面
ok到这为止就完成了,以后我们用到只要移植就可以了,怎么样,也很简单吧

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网