zoukankan      html  css  js  c++  java
  • 自定义view

    1:四个构造方法,其中有一个参数,两个参数,三个参数,四个参数;

    2:四个方法:1:onMeasuer()测量高度,2:onDraw()绘制需要一个画笔panit3:onLayout()定位,定位视图的位置,4:onTouchEvent()监听事件

    3:首先要学会画圆

    下面是一些代码

    <declare-styleable name="circleView"> <attr name="textSize" format="dimension" /> <attr name="text" format="string" /> <attr name="circleColor" format="color" /> <attr name="arcColor" format="color" /> <attr name="textColor" format="color" /> <attr name="startAngle" format="integer" /> <attr name="sweepAngle" format="integer" /> </declare-styleable>
      Ⅰ、textSize——对应中间文本文字的大小
      Ⅱ、text——对应中间文本
      Ⅲ、circleColor——对应内圆的颜色
      Ⅳ、arcColor——对应外环的颜色
      Ⅴ、textColor——对应文本的颜色
      Ⅵ、startAngle——对应外环的起始角度
      Ⅶ、sweepAngle——对应外环扫描角度
      紧接着,就是在自定义控件的初始化方法中来获取这些自定义属性:
    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.circleView); if (ta != null) { circleColor = ta.getColor(R.styleable.circleView_circleColor, 0); arcColor = ta.getColor(R.styleable.circleView_arcColor, 0); textColor = ta.getColor(R.styleable.circleView_textColor, 0); textSize = ta.getDimension(R.styleable.circleView_textSize, 50); text = ta.getString(R.styleable.circleView_text); startAngle = ta.getInt(R.styleable.circleView_startAngle, 0); sweepAngle = ta.getInt(R.styleable.circleView_sweepAngle, 90); ta.recycle(); }
      这里在多说一嘴子,为了释放更多的资源,一定要将TypedArray这个对象进行资源的释放。
      接下来,在OnMeasure()方法中,初始化要绘制画笔样式,获取屏幕的宽度,计算中间位置的坐标,以及指定外接矩形的宽高代码如下:
    private void init() { int length = Math.min(width, height); mCircleXY = length / 2; mRadius = length * 0.5f / 2; mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mCirclePaint.setColor(circleColor); mRectF = new RectF(length * 0.1f, length * 0.1f, length * 0.9f, length * 0.9f); mArcPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mArcPaint.setColor(arcColor); mArcPaint.setStyle(Paint.Style.STROKE); mArcPaint.setStrokeWidth((width * 0.1f)); mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mTextPaint.setTextSize(textSize); mTextPaint.setColor(textColor); mTextPaint.setTextAlign(Align.CENTER); }
      将我们设置的自定义属性,设置给不同笔刷。
      做了这么多准备以后,我们所需的就是在OnDraw方法中绘制内圆、外环与文字。代码如下:
    @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); drawSth(canvas); } private void drawSth(Canvas canvas) { canvas.drawCircle(mCircleXY, mCircleXY, mRadius, mCirclePaint); canvas.drawArc(mRectF, startAngle, sweepAngle, false, mArcPaint); canvas.drawText(text, 0, text.length(), mCircleXY, mCircleXY + textSize / 4, mTextPaint); }
  • 相关阅读:
    带密钥的sha1加密
    单调队列优化和二进制优化的多重背包模板
    HDU6424 Rikka with Time Complexity
    HDU6415 Rikka with Nash Equilibrium
    BZOJ1012: [JSOI2008]最大数maxnumber
    BZOJ2660: [Beijing wc2012]最多的方案
    读入优化和输出优化模板
    BZOJ1089: [SCOI2003]严格n元树
    2018 “百度之星”程序设计大赛
    JavaScript事件代理和委托(Delegation)
  • 原文地址:https://www.cnblogs.com/zzwerzi/p/7620317.html
Copyright © 2011-2022 走看看