美文网首页
自定义View入门(五) - 自定义View刷新

自定义View入门(五) - 自定义View刷新

作者: 黄烨1121 | 来源:发表于2017-11-02 10:36 被阅读0次

本章目录

  • Part One:invalidate刷新
  • Part Two:postInvalidate刷新

在自定义View中,常常需要用到刷新View的方法,比如说我们像官方控件一样,用setXx方法改变某个自定义属性的值,就要刷新View,重新绘制一遍。
而自定义View中,刷新View有三个方法:

  1. requestLayout:requestLayout会调用measure和layout 等一系列操作,然后根据布局是否发生改变,surface是否被销毁,来决定是否调用draw。
    也就是说requestLayout肯定会调用measure和layout,但是如果我们的布局没有发生改变(布局大小),只是改变位置,那么就不会调用draw,我们的自定义View不会被重新绘制。
  2. invalidate:只会调用draw,而且肯定会调,即使什么都没有发生改变,它也会重新绘制。
  3. postInvalidate:用法几乎和invalidate一样,只是invalidate用于UI(主)线程,而postInvalidate用于异步线程。

所以如果有布局需要发生改变,需要调用requestLayout方法,如果只是刷新动画,则只需要调用invalidate方法,而且也更高效。

Part One:invalidate刷新

我们先来看看invalidate方法,最简单的一个应用就是改变自定义属性的值了,我们来看下面画圆的这个案例。
原始的图形是这样的:


初始View.png

我们先在代码里加上setXXX方法,然后写上invalidate

    public void setRadius(float mRadius) {
        this.radius = mRadius;
        invalidate();//重绘
    }

    public void setCircleColor(int mCircleColor) {
        circlePaint.setColor(mCircleColor);
        invalidate();//重绘
    }

    public void setStrokeWidth(float mStrokeWidth) {
        circlePaint.setStrokeWidth(mStrokeWidth);
        invalidate();//重绘
    }

然后在onCreate里初始化控件,并修改属性值

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
    }

    private void initViews() {
        CircleView circleView = findViewById(R.id.circleView);
        circleView.setCircleColor(Color.parseColor("#3949AB"));
        circleView.setRadius(100);
        circleView.setStrokeWidth(2);
    }
}

最后的效果如下:


修改的View.png

好了,invalidate最简单的应用应该已经明白了。上一节,我们说要画一个动态的圆,我们用这个例子再深入理解一下。
首先是自定义View的代码部分:

public class CircleView extends View{
    //画圆的画笔
    private Paint circlePaint;
    //圆的半径
    private float radius;
    //圆的颜色
    private int circleColor;
    //圆的宽度
    private float strokeWidth;
    //动态圆的颜色
    private int progressColor;
    //动态圆的画笔
    private Paint progressPaint;
    //动态圆的当前进度值
    private int currentProgress;
    //动态圆的范围
    private RectF initRectF;

    public CircleView(Context context) {
        this(context, null);
    }

    public CircleView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public CircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initAttrs(context, attrs);
        initVariables();
    }

    private void initAttrs(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs,
                R.styleable.CircleView, 0, 0);//获取TypedArray对象
        radius = typedArray.getDimension(R.styleable.CircleView_radius,
                100);//获取半径,默认值为100
        strokeWidth = typedArray.getDimension(R.styleable.CircleView_strokeWidth,
                2);//获取圆环的宽度,默认为2
        circleColor = typedArray.getColor(R.styleable.CircleView_circleColor,
               Color.BLACK);//获取圆环的颜色,默认为红色
        progressColor = typedArray.getColor(R.styleable.CircleView_progressColor,
                Color.RED);//获取圆环的颜色,默认为红色
        typedArray.recycle();//TypedArray对象是共享的资源,所以在获取完值之后必须要调用recycle()方法来回收。
    }

    private void initVariables() {
        //创建画圆的画笔
        circlePaint = new Paint();
        circlePaint.setAntiAlias(true);//画笔去除锯齿
        circlePaint.setColor(circleColor);//画笔颜色为红色
        circlePaint.setStyle(Paint.Style.STROKE);//画的圆是空心圆,FILL为实心圆
        circlePaint.setStrokeWidth(strokeWidth);//设置圆的线条宽度为2

        //创建动态圆的范围
        initRectF = new RectF();

        //创建动态圆的画笔
        progressPaint = new Paint();
        progressPaint.setAntiAlias(true);//画笔去除锯齿
        progressPaint.setColor(progressColor);//画笔颜色为红色
        progressPaint.setStyle(Paint.Style.STROKE);//画的圆是空心圆,FILL为实心圆
        progressPaint.setStrokeWidth(strokeWidth);//设置圆的线条宽度为2
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //getSuggestedMinimumWidth用于返回View推荐的最小宽度
        int width = getMeasuresize(getSuggestedMinimumWidth(), widthMeasureSpec);
        //getSuggestedMinimumHeight用于返回View推荐的最小高度
        int height = getMeasuresize(getSuggestedMinimumHeight(), heightMeasureSpec);
        setMeasuredDimension(width, height);//必须调用此方法,否则会抛出异常
    }

    private int getMeasuresize(int size, int measureSpec) {
        int result = size;
        //从MeasureSpec中获取测量模式
        int specMode = MeasureSpec.getMode(measureSpec);
        //从MeasureSpec中获取测量大小
        int specSize = MeasureSpec.getSize(measureSpec);
        switch (specMode){
            //父容器没有对当前View有任何限制,要多大就多大,这种情况一般用于系统内部,表示一种测量状态。
            case MeasureSpec.UNSPECIFIED:
                result = size;//用推荐值即可
                break;
            //父容器已经检测出View所需要的精确大小,这个时候View的最终大小就是SpecSize的值。
            //对应match_parent和具体的数值。
            case MeasureSpec.EXACTLY:
                result = specSize;
                break;
            //父容器指定了一个可用大小即SpecSize,View的大小不能大于这个值。对应wrap_content。
            case MeasureSpec.AT_MOST:
                result = Math.min(200, specSize);
                break;
        }
        return result;
    }

    public void setRadius(float mRadius) {
        this.radius = mRadius;
        invalidate();//重绘
    }

    public void setCircleColor(int mCircleColor) {
        circlePaint.setColor(mCircleColor);
        invalidate();//重绘
    }

    public void setStrokeWidth(float mStrokeWidth) {
        circlePaint.setStrokeWidth(mStrokeWidth);
        invalidate();//重绘
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int minimum = Math.min(getWidth() / 2, getHeight() / 2);
        radius = radius <= minimum ? radius : minimum;
        //画圆
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, radius - strokeWidth / 2, circlePaint);

        //获取动态圆的矩形区域,此时getWidth才有值。
        initRectF.top = getWidth() / 2 - radius + strokeWidth / 2;
        initRectF.left = getHeight() / 2 - radius + strokeWidth / 2;
        initRectF.right = getWidth() / 2 + radius - strokeWidth / 2;
        initRectF.bottom = getHeight() / 2 + radius - strokeWidth / 2;

        //动态圆的总进度
        int totalProgress = 100;
        //本质其实是画一个圆弧形的矩形
        canvas.drawArc(initRectF, -90, ((float) currentProgress / totalProgress) * 360, false, progressPaint);
    }

    public void updateProgress(int progress) {
        this.currentProgress = progress;
        invalidate();
    }
}

代码和以前变化不大,加了一个自定义View的属性progressColor,还有动态圆的画笔以及区域。
这里需要提一下的就是drawArc方法,就是画弧线,它包含了5个参数:

  • RectF oval:就是椭圆的矩形区域,如果我们设定一个正方向区域,那么绘制的就是一个圆的弧线,否则即为椭圆的弧线。
  • float startAngle:起始的角度,0度角对应钟表的3点钟方向,所以起始位置为-90度。
  • float sweepAngle:就是前进的角度
  • boolean useCenter:true就是绘制扇形,false仅仅绘制弧线
  • Paint paint:就是画笔了。

接下来就是Activity里的事儿了。
实例化一个Handler传递和处理消息:

 private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            circleView.updateProgress(msg.what);
        }
    };

在onResume中创建异步线程,更新progress,然后发送给主线程接受并处理。

 @Override
    protected void onResume() {
        super.onResume();
        new Thread(new Runnable() {
            @Override
            public void run() {
                int temp = 0;
                while (temp <= 100){
                    Message msg = new Message();
                    msg.what = temp;
                    handler.sendEmptyMessage(temp++);
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

最终的效果图如下:


效果图.gif

Part Two:postInvalidate刷新

之前说过invalidate只能用于主线程,这就导致了我们执行异步任务的时候,需要通过Handler去传递消息,写起来非常麻烦。而postInvalidate可直接在异步线程调用,写起来就简单多了。
同样的案例,在自定义View中将invalidate替换为postInvalidate:

    public void updateProgress(int progress) {
        this.currentProgress = progress;
        postInvalidate();
    }

而Activity里的代码可简化为:

    @Override
    protected void onResume() {
        super.onResume();
        new Thread(new Runnable() {
            @Override
            public void run() {
                int temp = 0;
                while (temp <= 100){
                    circleView.updateProgress(temp++);
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

即可实现同样的效果。


自定义View的刷新已经讲完了,下一节说说绘制文字的事儿。

相关文章

网友评论

      本文标题:自定义View入门(五) - 自定义View刷新

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