自定义View_04(小试牛刀)圆形进度条

废话不多说先上效果.
有点类似于QQ的步数加载的那个效果.


效果图.gif

看到这样的一个效果的时候, 先来分析一波.

  • 有两个弧形, 暂且称为底部和顶部
  • 底部的弧形, 就是背景的那个, 应该是固定在界面上的.
  • 主要就是顶部的弧形绘制及动画.
  • 图形的中间是一个 textView, 随着内层弧形进度的改变而改变数值,

下面将详细说一下怎么实现我们分析出来的这几点.

1. 创建自定义控件属性文件 attrs

看效果图可以得知这个自定义View大概有以下几个属性.

  • 底部弧形的颜色
  • 顶部弧形的颜色
  • 弧形的宽度
  • 文本显示字体的大小
  • 文本字体的颜色.
    那么我们在res/values文件夹下创建一个 attrs 文件来声明这些属性

    
        
        
        
        
        
        
        
        
        
        
    

2. 创建自定义View类 MyView.java

  • 继承 View
  • 重写三个构造方法
  • 重写 onMeasure, onDraw 方法
  • 获取刚才我们自定义的属性.
public class MyView extends View {
    //默认的底部弧形颜色
    private int mBottomArcColor = Color.RED;
    //默认的顶部弧形颜色
    private int mTopArcColor = Color.BLUE;
    //默认文本字体大小
    private int mTextSize = 10;
    //默认弧形的边框大小
    private int mBorderWidth = 20;  //20px,要转dip
    //默认文本颜色
    private int mTextColor = Color.RED;

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

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

    public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttr(context, attrs);
    }

    private int sp2px(int sp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, getResources().getDisplayMetrics());
    }

    private void initAttr(Context context, AttributeSet attrs) {
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.myView);
        mBottomArcColor = array.getColor(R.styleable.myView_bottomArcColor, mBottomArcColor);
        mTopArcColor = array.getColor(R.styleable.myView_topArcColor, mTopArcColor);
        mBorderWidth = (int) array.getDimension(R.styleable.myView_borderWidth, mBorderWidth);
        mTextSize = array.getDimensionPixelSize(R.styleable.myView_myTextSize, sp2px(mTextSize));
        mTextColor = array.getColor(R.styleable.myView_myTextColor, mTextColor);
        array.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

}

准备阶段已经做完了, 下一步就要开始测量了.

3. onMeasure 开始测量

实际在开发过程中, 可能需要考虑到很多情况. 例如: 在外部对控件进行设置属性的时候, 调用者有可能会直接设置固定的宽高或者使用 wrap_content 又或者使用 match_parent. 这些都是不可预测的, 可以在 onMeasure 中通过判断宽高的mode 来进行一系列的操作(前两章已经讲过). 这里为了演示, 就不考虑外部设置的是不是 wrap_content / match_parent了. 就认定外部设置固定宽高.固定为正方形

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //获取设置的宽高
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);

        //设置宽高 , 采用最大的值
        setMeasuredDimension(width, height);
    }

4. onDraw 开始绘制

我们先从简单的开始 ,先绘制底部的弧形. 准备一个绘制底部的画笔

    private Paint mBottomArcPaint,
    /**
     * 底部弧形画笔设置 
     * 在 initAttr 方法中调用
     */    
    private void initBottomArcPaint() {
        mBottomArcPaint = new Paint();
        //设置抗锯齿
        mBottomArcPaint.setAntiAlias(true);
        //设置画笔宽度
        mBottomArcPaint.setStrokeWidth(mBorderWidth);
        //设置颜色
        mBottomArcPaint.setColor(mBottomArcColor);
        //设置画圆弧的画笔的属性为描边,空心
        //Paint.Style.STROKE 只绘制图形轮廓(描边)
        //Paint.Style.FILL 只绘制图形内容
        //Paint.Style.FILL_AND_STROKE 既绘制轮廓也绘制内容
        mBottomArcPaint.setStyle(Paint.Style.STROKE);
        //设置画笔始末端样式为圆形
        mBottomArcPaint.setStrokeCap(Paint.Cap.ROUND);
    }
4.1 开始绘制底部圆弧
   @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //设置落笔的上下左右, 需要考虑到画笔宽度
        RectF rectF = new RectF(mBorderWidth / 2, mBorderWidth / 2,
                getWidth() - mBorderWidth / 2, getHeight() - mBorderWidth / 2);

        canvas.drawArc(rectF, 135, 270, false, mBottomArcPaint);
    }

有些朋友要问了, 为什么绘制的大小要边框大小 / 2 呢.

因为笔触的宽度, 并不是往笔触内侧增加宽度的, 而是外侧一半, 内侧一半

drawArc 参数说明

  • 参数1: 定义圆弧的形状和大小的范围
  • 参数2: 设置圆弧是从哪个角度来顺时针绘画的
  • 参数3: 设置圆弧扫过的角度
  • 参数4: 圆弧在绘画的时候,是否经过圆心
  • 参数5: 画笔

那么为什么是从135°开始, 顺时针画270°呢 ? 看下图



开始扫描的角度是 180° - 45° = 135°
扫的范围就是 360° - 90°(缺的那块的) = 270°

这个时候可以运行一下看一下效果, 如下图



底部的弧形已经绘制好了, 现在开始绘制顶部的圆弧.

4.2 绘制顶部圆弧

内圆弧的扫描角度, 是不能写死的. 需要外部传入进来, 所以就需要设置两个变量, 一个是总进度, 一个是当前进度.当然, 还需要一个绘制顶部的圆弧的画笔

    //总进度
    private int mToalProgress = 0;
    //当前进度
    private int mCurrentProgress = 0;
    //顶部画笔
    private Paint mTopArcPaint;
    /**
     * 顶部弧形画笔设置 
     * 在 initAttr 方法中调用
     */    
    private void initTopArcPaint() {
        mTopArcPaint= new Paint();
        mTopArcPaint.setAntiAlias(true);
        mTopArcPaint.setStrokeWidth(mBorderWidth);
        mTopArcPaint.setColor(mTopArcColor);
        mTopArcPaint.setStyle(Paint.Style.STROKE);
        mTopArcPaint.setStrokeCap(Paint.Cap.ROUND);
    }
       @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //绘制底部圆弧
        ...
        //绘制顶部圆弧, 如果总进度是 0 那么直接不继续绘制
        if (mToalProgress == 0){
             return;
        }
        float sweepAngle = (float) mCurrentProgress / mToalProgress;
        canvas.drawArc(rectF, 135, sweepAngle * 270, false, mTopArcPaint);

    }

为了看到效果, 我们先给总进度设置为100, 当前进度设置为60, 运行一下看下效果.



OK, 就是这样, 下面还剩最后一个, 就是中间的文字

4.3 绘制中间进度显示文本

首先是 文字画笔设置

    private Paint mTextPaint;
    private void initTextPaint() {
        mTextPaint = new Paint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setColor(mTextColor);
        mTextPaint.setTextSize(mTextSize);
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //画底部圆弧
        ...
        //画顶部圆弧
        ...
        //画文字
        String str = mCurrentProgress + "";
        //测量文字的宽度
        Rect textBounds = new Rect();
        mTextPaint.getTextBounds(str , 0, str .length(), textBounds);
        //开始绘制文字的位置
        int dx = getWidth() / 2 - textBounds.width() / 2;
        //基线
        Paint.FontMetricsInt metricsInt = mTextPaint.getFontMetricsInt();
        int dy = (metricsInt.bottom - metricsInt.top) / 2 - metricsInt.bottom;
        int basrLine = getHeight() / 2 + dy;
        canvas.drawText(str , dx, basrLine, mTextPaint);
   }

还需要加入两个方法, 来设置总进度和当前进度的值

    public synchronized void setToalProgress(int toal) {
        this.mToalProgress = toal;
    }

    public synchronized void setCurrentProgress(int currentProgress) {
        this.mCurrentProgress = currentProgress;
        //不断绘制,会不断的去调用onDraw
        invalidate();
    }

至此这个自定义View 已经算是完成了, 剩下的就是外面的调用了.
布局文件




    

MainActivity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final MyView myView = findViewById(R.id.myView);
        myView.setToalProgress(100);

        //设置属性动画
        ValueAnimator valueAnimator = ObjectAnimator.ofFloat(0, 80);
        valueAnimator.setDuration(2000);
        //设置差值器, 由快变慢
        valueAnimator.setInterpolator(new DecelerateInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float  value = (float) animation.getAnimatedValue();
                myView.setCurrentProgress((int)value);
            }
        });
        valueAnimator.start();
    }
}

OK, 这个小试牛刀的自定义View就完成了.
稍后会放上代码的Git地址.

你可能感兴趣的:(自定义View_04(小试牛刀)圆形进度条)