当前位置: 移动技术网 > IT编程>移动开发>Android > Android自定义View绘制随机生成图片验证码

Android自定义View绘制随机生成图片验证码

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

变脸迷情国语,学生手册家长评语,劣质人头石像

本篇文章讲的是android自定义view之随机生成图片验证码,开发中我们会经常需要随机生成图片验证码,但是这个是其次,主要还是想总结一些自定义view的开发过程以及一些需要注意的地方。

按照惯例先看看效果图:


一、先总结下自定义view的步骤:

1、自定义view的属性
2、在view的构造方法中获得我们自定义的属性
3、重写onmesure
4、重写ondraw
其中onmesure方法不一定要重写,但大部分情况下还是需要重写的

二、view 的几个构造函数

1、public customview(context context)
—>java代码直接new一个customview实例的时候,会调用这个只有一个参数的构造函数;
2、public customview(context context, attributeset attrs)
—>在默认的xml布局文件中创建的时候调用这个有两个参数的构造函数。attributeset类型的参数负责把xml布局文件中所自定义的属性通过attributeset带入到view内;
3、public customview(context context, attributeset attrs, int defstyleattr)
—>构造函数中第三个参数是默认的style,这里的默认的style是指它在当前application或者activity所用的theme中的默认style,且只有在明确调用的时候才会调用
4、public customview(context context, attributeset attrs, int defstyleattr, int defstyleres)
—>该构造函数是在api21的时候才添加上的

三、下面我们就开始来看看代码啦

1、自定义view的属性,首先在res/values/ 下建立一个attr.xml , 在里面定义我们的需要用到的属性以及声明相对应属性的取值类型

<?xml version="1.0" encoding="utf-8"?>
<resources>

 <attr name="text" format="string" />
 <attr name="textcolor" format="color" />
 <attr name="textsize" format="dimension" />
 <attr name="bgcolor" format="color" />

 <declare-styleable name="customview">
  <attr name="text" />
  <attr name="textcolor" />
  <attr name="textsize" />
  <attr name="bgcolor" />
 </declare-styleable>

</resources>

我们定义了字体,字体颜色,字体大小以及字体的背景颜色4个属性,format是值该属性的取值类型,format取值类型总共有10种,包括:string,color,demension,integer,enum,reference,float,boolean,fraction和flag。

2、然后在xml布局中声明我们的自定义view

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:custom="http://schemas.android.com/apk/res-auto"
 android:layout_width="match_parent"
 android:layout_height="match_parent">

 <com.per.customview01.view.customview
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_centerinparent="true"
  android:padding="10dp"
  custom:bgcolor="#ff27ff28"
  custom:text="j2rdwqg"
  custom:textcolor="#ff0000"
  custom:textsize="36dp" />

</relativelayout>

一定要引入xmlns:custom=”http://schemas.android.com/apk/res-auto”,android studio中我们可以使用res-atuo命名空间,就不用在添加自定义view全类名。

3、在view的构造方法中,获得我们的自定义的样式

/**
  * 文本
  */
 private string mtext;
 /**
  * 文本的颜色
  */
 private int mtextcolor;
 /**
  * 文本的大小
  */
 private int mtextsize;
 /**
  * 文本的背景颜色
  */
 private int mbgcplor;
 private rect mbound;
 private paint mpaint;

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

 public customview(context context, attributeset attrs) {
  this(context, attrs, 0);
 }

 public customview(context context, attributeset attrs, int defstyleattr) {
  super(context, attrs, defstyleattr);
  /**
   * 获得我们所定义的自定义样式属性
   */
  typedarray a = context.gettheme().obtainstyledattributes(attrs, r.styleable.customview, defstyleattr, 0);
  for (int i = 0; i < a.getindexcount(); i++) {
   int attr = a.getindex(i);
   switch (attr) {
    case r.styleable.customview_text:
     mtext = a.getstring(attr);
     break;
    case r.styleable.customview_textcolor:
     // 默认文本颜色设置为黑色
     mtextcolor = a.getcolor(r.styleable.customview_textcolor, color.black);
     break;
    case r.styleable.customview_bgcolor:
     // 默认文本背景颜色设置为蓝色
     mbgcplor = a.getcolor(r.styleable.customview_bgcolor, color.blue);
     break;
    case r.styleable.customview_textsize:
     // 默认设置为16sp,typevalue也可以把sp转化为px
     mtextsize = a.getdimensionpixelsize(attr, (int) typedvalue.applydimension(typedvalue.complex_unit_sp, 16, getresources().getdisplaymetrics()));
     break;
   }
  }
  a.recycle();
  // 获得绘制文本的宽和高
  mpaint = new paint();
  mpaint.settextsize(mtextsize);

  mbound = new rect();
  mpaint.gettextbounds(mtext, 0, mtext.length(), mbound);
 }

我们重写了3个构造方法,在上面的构造方法中说过默认的布局文件调用的是两个参数的构造方法,所以记得让所有的构造方法调用三个参数的构造方法,然后在三个参数的构造方法中获得自定义属性。
一开始一个参数的构造方法和两个参数的构造方法是这样的:

 public customview(context context) {
  super(context);
 }

 public customview(context context, attributeset attrs) {
  super(context, attrs);
 }

有一点要注意的是super应该改成this,然后让一个参数的构造方法引用两个参数的构造方法,两个参数的构造方法引用三个参数的构造方法,代码如下:

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

 public customview(context context, attributeset attrs) {
  this(context, attrs, 0);
 }
 

4、重写ondraw,onmesure方法

@override
 protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
  super.onmeasure(widthmeasurespec, heightmeasurespec);
 }

 @override
 protected void ondraw(canvas canvas) {
  super.ondraw(canvas);
  mpaint.setcolor(mbgcplor);
  canvas.drawrect(0, 0, getmeasuredwidth(), getmeasuredheight(), mpaint);

  mpaint.setcolor(mtextcolor);
  canvas.drawtext(mtext, getwidth() / 2 - mbound.width() / 2, getheight() / 2 + mbound.height() / 2, mpaint);
 }

view的绘制流程是从viewroot的performtravarsals方法开始的,经过measure、layout和draw三个过程才能最终将一个view绘制出来,其中:
 •测量——onmeasure():用来测量view的宽和高来决定view的大小
 •布局——onlayout():用来确定view在父容器viewgroup中的放置位置
 •绘制——ondraw():负责将view绘制在屏幕上

来看下此时的效果图


细心的朋友会发现,在上面的布局文件中,我们是把宽和高设置为wrap_content的,可是这个效果图怎么看都不是我们想要的,这是因为系统帮我们测量的高度和宽度默认是match_parnet,当我们设置明确的宽度和高度时,系统帮我们测量的结果就是我们设置的结果,这个是对的。但是除了设置明确的宽度和高度,不管我们设置为wrap_content还是match_parent,系统帮我们测量的结果就是match_parent,所以,当我们设置了wrap_content时,我们需要自己进行测量,也就是说我们需要重写onmesure方法

下面是我们重写onmeasure代码:

 @override
 protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
  super.onmeasure(widthmeasurespec, heightmeasurespec);
  int widthmode = measurespec.getmode(widthmeasurespec);
  int widthsize = measurespec.getsize(widthmeasurespec);
  int heighmode = measurespec.getmode(heightmeasurespec);
  int heighsize = measurespec.getsize(heightmeasurespec);
  setmeasureddimension(widthmode == measurespec.exactly ? widthsize : getpaddingleft() + getpaddingright() + mbound.width(), heighmode == measurespec.exactly ? heighsize : getpaddingtop() + getpaddingbottom() + mbound.height());
 }

measurespec封装了父布局传递给子布局的布局要求,measurespec的specmode一共有三种模式:
(1)exactly(完全):一般是设置了明确的值或者是match_parent,父元素决定了子元素的大小,子元素将被限定在给定的范围里而忽略它本身大小;
(2)at_most(至多):表示子元素至多达到给定的一个最大值,一般为warp_content;

我们再看看效果图:

现在这个是我们想要的结果了吧,回归到主题,今天讲的是自定义view之随机生成图片验证码,现在把自定义view的部分完成了,我把完整的代码贴出来

package com.per.customview01.view;

import android.content.context;
import android.content.res.typedarray;
import android.graphics.canvas;
import android.graphics.color;
import android.graphics.paint;
import android.graphics.rect;
import android.util.attributeset;
import android.util.log;
import android.util.typedvalue;
import android.view.view;

import com.per.customview01.r;

import java.util.random;

/**
 * @author: adan
 * @description:
 * @projectname: customview01
 * @date: 2016-06-12
 * @time: 10:26
 */
public class customview extends view {
 private static final char[] chars = {'0', '1', '2', '3', '4', '5', '6',
   '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
   'k', 'l', 'm', 'n', 'o', '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', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
   'x', 'y', 'z'};
 /**
  * 初始化生成随机数的类
  */
 private random mrandom = new random();
 /**
  * 初始化可变字符串
  */
 private stringbuffer sb = new stringbuffer();
 /**
  * 文本
  */
 private string mtext;
 /**
  * 文本的颜色
  */
 private int mtextcolor;
 /**
  * 文本的大小
  */
 private int mtextsize;
 /**
  * 文本的背景颜色
  */
 private int mbgcplor;
 private rect mbound;
 private paint mpaint;

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

 public customview(context context, attributeset attrs) {
  this(context, attrs, 0);
 }

 public customview(context context, attributeset attrs, int defstyleattr) {
  super(context, attrs, defstyleattr);
  /**
   * 获得我们所定义的自定义样式属性
   */
  typedarray a = context.gettheme().obtainstyledattributes(attrs, r.styleable.customview, defstyleattr, 0);
  for (int i = 0; i < a.getindexcount(); i++) {
   int attr = a.getindex(i);
   switch (attr) {
    case r.styleable.customview_text:
     mtext = a.getstring(attr);
     break;
    case r.styleable.customview_textcolor:
     // 默认文本颜色设置为黑色
     mtextcolor = a.getcolor(r.styleable.customview_textcolor, color.black);
     break;
    case r.styleable.customview_bgcolor:
     // 默认文本背景颜色设置为蓝色
     mbgcplor = a.getcolor(r.styleable.customview_bgcolor, color.blue);
     break;
    case r.styleable.customview_textsize:
     // 默认设置为16sp,typevalue也可以把sp转化为px
     mtextsize = a.getdimensionpixelsize(attr, (int) typedvalue.applydimension(typedvalue.complex_unit_sp, 16, getresources().getdisplaymetrics()));
     break;
   }
  }
  a.recycle();
  // 获得绘制文本的宽和高
  mpaint = new paint();
  mpaint.settextsize(mtextsize);

  mbound = new rect();
  mpaint.gettextbounds(mtext, 0, mtext.length(), mbound);

  this.setonclicklistener(new onclicklistener() {
   @override
   public void onclick(view v) {
    mtext = createcode();
    mtextcolor = randomcolor();
    mbgcplor = randomcolor();
    //view重新调用一次draw过程,以起到界面刷新的作用
    postinvalidate();
   }
  });
 }

 /**
  * 生成验证码
  */
 public string createcode() {
  sb.delete(0, sb.length()); // 使用之前首先清空内容
  for (int i = 0; i < 6; i++) {
   sb.append(chars[mrandom.nextint(chars.length)]);
  }
  log.e("生成验证码", sb.tostring());
  return sb.tostring();
 }

 /**
  * 随机颜色
  */
 private int randomcolor() {
  sb.delete(0, sb.length()); // 使用之前首先清空内容
  string haxstring;
  for (int i = 0; i < 3; i++) {
   haxstring = integer.tohexstring(mrandom.nextint(0xff));
   if (haxstring.length() == 1) {
    haxstring = "0" + haxstring;
   }
   sb.append(haxstring);
  }
  log.e("随机颜色", "#" + sb.tostring());
  return color.parsecolor("#" + sb.tostring());
 }

 @override
 protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
  super.onmeasure(widthmeasurespec, heightmeasurespec);
  int widthmode = measurespec.getmode(widthmeasurespec);
  int widthsize = measurespec.getsize(widthmeasurespec);
  int heighmode = measurespec.getmode(heightmeasurespec);
  int heighsize = measurespec.getsize(heightmeasurespec);
  setmeasureddimension(widthmode == measurespec.exactly ? widthsize : getpaddingleft() + getpaddingright() + mbound.width(), heighmode == measurespec.exactly ? heighsize : getpaddingtop() + getpaddingbottom() + mbound.height());
 }

 @override
 protected void ondraw(canvas canvas) {
  super.ondraw(canvas);
  mpaint.setcolor(mbgcplor);
  canvas.drawrect(0, 0, getmeasuredwidth(), getmeasuredheight(), mpaint);

  mpaint.setcolor(mtextcolor);
  canvas.drawtext(mtext, getwidth() / 2 - mbound.width() / 2, getheight() / 2 + mbound.height() / 2, mpaint);
 }
}

我们添加了一个点击事件,每一次点击view我都让它把生成的验证码和字体颜色以及字体背景颜色打印出来,如下所示:

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

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

相关文章:

验证码:
移动技术网