自定义控件起步(三)--自定义验证码(上)

自定义控件前两篇主要介绍了自定义控件的步骤和自定义属性,这篇我门来写一个自定义验证码

首先,先分析分析我门需要什么:

      自定义验证码,我门需要先画一段文字,准确的说是四个数字或字母,还需要一个灰色的背景.

      说的详细点,我门需要一个验证码字体颜色 ,字体大小.字体的内容我门先写死,等内容画出

      来了,我门在代码中结合随机数生成

接下来,我门看具体步骤

    1.声明两个自定义属性   分别是验证码字体颜色和字体大小

     在values下创建一个attrs的xml文件夹,在<resources>中添加自定义属性

    <declare-styleable name="securitycode">
        <attr name="security_text_color" format="color" />
        <attr name="security_text_size" format="dimension" />
    </declare-styleable>
    2.创建自定义控件类 SecurityCodeView,继承view,声明三个构造方法,这跟之前的一样

        public SecurityCodeView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}
	public SecurityCodeView(Context context) {
		this(context, null, 0);
	}
        public SecurityCodeView(Context context, AttributeSet attrs,
            int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        }
     3.使用自定义属性

        先声明命名空间   xmlns:dsecurity="http://schemas.android.com/apk/res/com.example.defindedsecuritycode"
       
            <com.example.defindedsecuritycode.SecurityCodeView
                android:id="@+id/security_code"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                dsecurity:security_text_color="#999999"
                dsecurity:security_text_size="40sp">
            </com.example.defindedsecuritycode.SecurityCodeView>
    4.在构造方法中获取自定义属性  
                // 获取自定义属性值 验证码字体颜色,大小,内容
		TypedArray typedArray = context.getTheme().obtainStyledAttributes(
				attrs, R.styleable.securitycode, defStyleAttr, 0);
                security_color = typedArray.getColor(
                R.styleable.securitycode_security_text_color, Color.BLACK);
           security_size = typedArray.getDimensionPixelSize(
                R.styleable.securitycode_security_text_size, (int) TypedValue
                        .applyDimension(TypedValue.COMPLEX_UNIT_SP, 16,
                                getResources().getDisplayMetrics()));
        typedArray.recycle();//一定记得回收
     5.在构造方法中进行一些初始化操作

             Paint mPaint  = new Paint();// 创建画笔
        mPaint.setTextSize(security_size);// 设置字体大小
        security_rect = new Rect();// 创建一个矩形
        mPaint.getTextBounds(security_text, 0, security_text.length(),
                security_rect);// 根据文字的大小设置矩形的大小();// 创建画笔
           String security_text="";//这里我们先把验证码的文字写死

       这里创建的这个矩形就是等会我们要画的灰色阴影部分,我们根据文本字体的大小和文本的长度来设置阴影部分矩形的大小 

      6.测量控件的大小

	/**
	 * 测量大小 根据宽或者高的模式来确定自定义控件大小
	 */
	@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);
		int width;
		int height;
		if (widthMode == MeasureSpec.EXACTLY) {// 如果确定大小 不用计算
			width = widthSize;
		} else {// 大小不确定 根据验证码的宽度来确定
			mPaint.setTextSize(security_size);
			mPaint.getTextBounds(security_text, 0, security_text.length(),
					security_rect);
			int textWidth = security_rect.width();
			int realWidth = textWidth + getPaddingLeft() + getPaddingRight();
			width = realWidth;
		}
		if (heightMode == MeasureSpec.EXACTLY) {
			height = heightSize;
		} else {
			mPaint.setTextSize(security_size);
			mPaint.getTextBounds(security_text, 0, security_text.length(),
					security_rect);
			int textheight = security_rect.height();
			int realHeight = textheight + getPaddingBottom() + getPaddingTop();
			height = realHeight;
		}
		setMeasuredDimension(width, height);// 将确定好的长和宽告设置上去
	}
            注意:这里我们根据文字的大小和长度来测量控件的大小

       7.开始画我们的自定控件(非常关键的一步)

                // 设置验证码背景颜色,并画出来
		mPaint.setColor(Color.parseColor("#e1e1e1"));//背景颜色是灰色的,直接写死
		canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint);

		// 设置验证码颜色,并画出来
		mPaint.setColor(security_color);
		canvas.drawText(security_text, getWidth() / 2 - security_rect.width()
				/ 2, getHeight() / 2 + security_rect.height() / 2, mPaint);
       问题一: 为什么矩形的宽度和高度等同于整个控件的高度?

     这里的矩形,实际上是我们看到的阴影部分,阴影部分的高度是大于文字的高度的,阴影部分的高度也是整个验证码的高度

       问题二:字体的高度和宽度  

   

           注意:因为咱们重写了onMeasure方法,所以,测量的宽度getMeasuredWidth和getWidth()是一样的

       问题三:我能不能先画文字,再画背景?

       不能,如果先画文字再画背景,背景会把文字遮住的,我们就只能看到背景,而看不到文字了

    8.运行,,看一下效果吧


    到这里我们自定义验证码的雏形就显示出来了,但是还有几个问题,怎么设置验证码的了类型,点击切换等,这些下一篇会介绍


   点击这里下载源码



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值