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

本篇文章讲的是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我都让它把生成的验证码和字体颜色以及字体背景颜色打印出来,如下所示:

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

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索android
view图片验证码
自定义view的绘制流程、自定义view 绘制 动画、自定义view清除绘制、自定义view绘制、自定义验证码输入view,以便于您获取更多的相关知识。

时间: 2024-07-29 11:55:50

Android自定义View绘制随机生成图片验证码_Android的相关文章

Android自定义view制作绚丽的验证码_Android

废话不多说了,先给大家展示下自定义view效果图,如果大家觉得还不错的话,请继续往下阅读. 怎么样,这种验证码是不是很常见呢,下面我们就自己动手实现这种效果,自己动手,丰衣足食,哈哈~ 一. 自定义view的步骤 自定义view一直被认为android进阶通向高手的必经之路,其实自定义view好简单,自定义view真正难的是如何绘制出高难度的图形,这需要有好的数学功底(后悔没有好好学数学了~),因为绘制图形经常要计算坐标点及类似的几何变换等等.自定义view通常只需要以下几个步骤: 写一个类继承

Android自定义view制作绚丽的验证码

废话不多说了,先给大家展示下自定义view效果图,如果大家觉得还不错的话,请继续往下阅读. 怎么样,这种验证码是不是很常见呢,下面我们就自己动手实现这种效果,自己动手,丰衣足食,哈哈~ 一. 自定义view的步骤 自定义view一直被认为android进阶通向高手的必经之路,其实自定义view好简单,自定义view真正难的是如何绘制出高难度的图形,这需要有好的数学功底(后悔没有好好学数学了~),因为绘制图形经常要计算坐标点及类似的几何变换等等.自定义view通常只需要以下几个步骤: 写一个类继承

Android自定义View编写随机验证码_Android

很多的Android入门程序猿来说对于Android自定义View,可能都是比较恐惧的,但是这又是高手进阶的必经之路,所有准备在自定义View上面花一些功夫,多写一些文章.先总结下自定义View的步骤: 1.自定义View的属性 2.在View的构造方法中获得我们自定义的属性[ 3.重写onMesure ] 4.重写onDraw 我把3用[]标出了,所以说3不一定是必须的,当然了大部分情况下还是需要重写的. 1.自定义View的属性,首先在res/values/  下建立一个attrs.xml

Android自定义View软键盘实现搜索_Android

1. xml文件中加入自定义 搜索view <com.etoury.etoury.ui.view.IconCenterEditText android:id="@+id/search_et" style="@style/StyleEditText" android:hint="搜索景点信息" /> 2. 自定义的   view java文件 IconCenterEditText.java package com.etoury.etou

Android自定义View实现水面上涨效果_Android

实现效果如下: 实现思路: 1.如何实现圆中水面上涨效果:利用Paint的setXfermode属性为PorterDuff.Mode.SRC_IN画出进度所在的矩形与圆的交集实现 2.如何水波纹效果:利用贝塞尔曲线,动态改变波峰值,实现"随着进度的增加,水波纹逐渐变小的效果" 话不多说,看代码. 首先是自定义属性值,有哪些可自定义属性值呢? 圆的背景颜色:circle_color,进度的颜色:progress_color,进度显示文字的颜色:text_color,进度文字的大小:tex

Android自定义View实现折线图效果_Android

下面就是结果图(每种状态用一个表情图片表示): 一.主页面的布局文件如下: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height=&quo

Android 自定义View 密码框实例代码_Android

暴露您view中所有影响可见外观的属性或者行为. •通过XML添加和设置样式 •通过元素的属性来控制其外观和行为,支持和重要事件交流的事件监听器 详细步骤见:Android 自定义View步骤 效果图展示: 支持的样式 可以通过XML定义影响外边和行为的属性如下 边框圆角值,边框颜色,分割线颜色,边框宽度,密码长度,密码大小,密码颜色 <declare-styleable name="PasswordInputView"> <attr name="borde

Android自定义View绘制的方法及过程(二)

上一篇<Android 自定义View(一) Paint.Rect.Canvas介绍>讲了最基础的如何自定义一个View,以及View用到的一些工具类.下面讲下View绘制的方法及过程 public class MyView extends View { private String TAG = "--------MyView"; private int width, height; public MyView(Context context, AttributeSet a

Android自定义View实现字母导航栏_Android

很多的Android入门程序猿来说对于Android自定义View,可能都是比较恐惧的,但是这又是高手进阶的必经之路,所有准备在自定义View上面花一些功夫,多写一些文章. 思路分析: 1.自定义View实现字母导航栏 2.ListView实现联系人列表 3.字母导航栏滑动事件处理 4.字母导航栏与中间字母的联动 5.字母导航栏与ListView的联动 效果图: 首先,我们先甩出主布局文件,方便后面代码的说明 <!--?xml version="1.0" encoding=&qu