自定义View(实现随机二维码)

背景

最近在重温自定义View的伟大,这篇文章是从自己其他的博客搬过来,有些格式可能不太好,大家将就,最后又demo的下载地址,也欢迎下载,有问题欢迎指出,一起交流:

开始啦

对于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到这为止就完成了,以后我们用到只要移植就可以了,怎么样,也很简单吧
    最后效果图
    demo下载地址:http://download.csdn.net/detail/u013243573/9575445
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,826评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,968评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,234评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,562评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,611评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,482评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,271评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,166评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,608评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,814评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,926评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,644评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,249评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,866评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,991评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,063评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,871评论 2 354

推荐阅读更多精彩内容