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

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

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

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

按照惯例先看看效果图:


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

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

二、VIEw 的几个构造函数
@H_403_13@

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,int defStyleAttr,int defStyleRes)
―>该构造函数是在API21的时候才添加上的

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

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>

我们定义了字体,字体颜色,@R_502_6860@以及字体的背景颜色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,int defStyleAttr) {  super(context,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,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,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,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,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,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,heighMode == MeasureSpec.EXACTLY ? heighSize : getpaddingtop() + getpaddingBottom() + mBound.height()); } @OverrIDe protected voID onDraw(Canvas canvas) {  super.onDraw(canvas);  mPaint.setcolor(mBgCplor);  canvas.drawRect(0,mPaint); }}

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的Android自定义View绘制随机生成图片验证码全部内容,希望文章能够帮你解决Android自定义View绘制随机生成图片验证码所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/web/1141563.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存