仿QQ步数进度条

2018-05-02  本文已影响0人  patient烽

1.演示效果

stepView.gif

2.效果分析

  1. 需要先画完整的圆环
  2. 画进度背景
  3. 画中间显示步数的文字
  4. 提供一些方法来设置最大步数,和当前步数

3.实现效果

  1. 先将宽度和高度设置为一样,可以美观一些
@Override
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
      final int width = MeasureSpec.getSize(widthMeasureSpec);
      final int height = MeasureSpec.getSize(heightMeasureSpec);
      setMeasuredDimension(width > height ? height : width, width > height ? height : width);
 }
  1. 画背景圆弧
// 画最外圈的圆(背景)  
    private void drawOuter(Canvas canvas) {
        mProgressPaint.setColor(mOuterColor);
        //距离view边框一些距离,RectF(left,top,right,bottom)四个参数分别为四个顶点
        this.mProgressRectF = new RectF(mBorderWidth, mBorderWidth,
                getWidth() - mBorderWidth, getHeight() - mBorderWidth);
        //  drawArc(RectF oval, float startAngle, float sweepAngle, boolean useCenter)  startAngle:开始角度:顺时针为正 sweepAngle:需要画圆弧的角度 useCenter:是否连接圆心
        canvas.drawArc(mProgressRectF, 135, 270, false, mOuterPaint);
}
  1. 画当前进度圆弧
private void drawInner(Canvas canvas) {
        //当没有设置当前最大步数,return
        if (mMaxStepCount == 0) {
            return;
        }
        //设置画当前进度圈画笔的颜色
        mProgressPaint.setColor(mInnerColor);
        //设置当前的进度
        final float progress = (mCurrentStepCount / mMaxStepCount);
        canvas.drawArc(mProgressRectF, 135, progress * 270, false, mProgressPaint);
    }

4.画进度值的文字

private void drawStepText(Canvas canvas) {
        final String strStepCount = String.valueOf((int) mCurrentStepCount);
        //测量获取文字的宽度
        mTextPaint.getTextBounds(strStepCount, 0, strStepCount.length(), mTextRect);
        //获取基线baseline
        final Paint.FontMetrics metrics = mTextPaint.getFontMetrics();
        final float dy = (metrics.bottom - metrics.top) / 2;
        canvas.drawText(strStepCount, getWidth() / 2 - mTextRect.width() / 2, getHeight() / 2 + dy,
                mTextPaint);
    }
  1. 提供一些方法,设置总步数和当前部分,供外部调用
 / **
   * 设置总的步数
   * @param maxStepCount 总的步数
   * /
  public void setMaxStepCount(float maxStepCount) {
        this.mMaxStepCount = maxStepCount;
    }

    /**
     * 设置当前的步数
     * @param currentStepCount 当前的步数
     */
    public void setCurrentStepCount(float currentStepCount) {
        this.mCurrentStepCount = currentStepCount;
        //可以使页面重绘制,重新调用onDraw()方法
        invalidate();
    }
上一篇下一篇

猜你喜欢

热点阅读