美文网首页
自定义View 一

自定义View 一

作者: coke613 | 来源:发表于2017-08-29 17:40 被阅读0次

    如果android自身的控件满足不了我们的需求时,这时我们应当考虑自定义view

    继承view或者是ViewGroup,实现自定义。

    两者区别:
    ①.直接继承view,在android中所有控件的基类都是view,相当于java中的object。
    ②.继承ViewGroup,例如线性布局,相对布局。像这种可以包裹子孩子的view的需求可以继承ViewGroup,它的父类也是View。

    实现构造方法小技巧:

    ★ 少参使用this调用多参。最多的参数使用super调用父类构造。
    这样写的好处是:无论你是创建对象还是在布局中使用,构造函数之间会相互调用,都会执行构造中的方法。

    private Paint mPaint;
      private Path mPath;
    
      public CanvasTestView(Context context) {
          this(context, null);          // 少参调用多参
      }
    
      public CanvasTestView(Context context, AttributeSet attrs) {
          this(context, attrs, 0);
      }
    public CanvasTestView(Context context, AttributeSet attrs, int defStyleAttr) {
          super(context, attrs, defStyleAttr);    //最后调用父类的多参构造
          init();
      }
    
      private void init() {
          //初始化画笔等。
          mPaint = new Paint();
          mPaint.setColor(Color.RED);
          mPaint.setStyle(Paint.Style.STROKE); // 设置画笔的样式
          mPaint.setAntiAlias(true);  // 去除锯齿,但会加大内存,不建议
          // 初始化路径
          mPath = new Path();
      }
      
        //该类用于封装坐标
      PointF startLine1 = new PointF(240, 230);
      PointF endLine1 = new PointF(450, 230);
      PointF circlePoint1 = new PointF(350, 350);
      PointF startLine2 = new PointF(345, 230);
      PointF endLine2 = new PointF(345, 450);
      PointF endLine3 = new PointF(315, 420);
      PointF circlePoint2 = new PointF(280, 310);
      PointF circlePoint3 = new PointF(410, 310);
      PointF arcPoint = new PointF(280, 490);
      PointF arcPoint2 = new PointF(410, 490);
    
      @Override
      protected void onDraw(Canvas canvas) {
          super.onDraw(canvas);
          canvas.drawCircle(circlePoint1.x, circlePoint1.y, 200, mPaint);
          canvas.drawLine(startLine1.x, startLine1.y, endLine1.x, endLine1.y, mPaint);
          canvas.drawLine(startLine2.x, startLine2.y, endLine2.x, endLine2.y, mPaint);
          canvas.drawLine(endLine2.x, endLine2.y, endLine3.x, endLine3.y, mPaint);
          canvas.drawCircle(circlePoint2.x, circlePoint2.y, 50, mPaint);
          canvas.drawCircle(circlePoint3.x, circlePoint3.y, 50, mPaint);
    
          canvas.drawCircle(circlePoint2.x, circlePoint2.y, 10, mPaint);
          canvas.drawCircle(circlePoint3.x, circlePoint3.y, 10, mPaint);
    
          mPath.moveTo(arcPoint.x, arcPoint.y);
          mPath.quadTo(arcPoint2.x, arcPoint2.y,445,440);
          canvas.drawPath(mPath,mPaint);
      }
    
    效果图

    相关文章

      网友评论

          本文标题:自定义View 一

          本文链接:https://www.haomeiwen.com/subject/dcqadxtx.html