热门搜索 :
考研考公
您的当前位置:首页正文

圆形百分比进度条(避坑笔记)

来源:东饰资讯网
这里写图片描述
进度的确出来了,可为什么显示的值不对呢?原数据是 0、10、12、4、,怎么现在全部少了1,找呀找呀发现了CirclePercentView类中的实现方法中有这么一段
 //内部设置百分比 用于动画效果
    private void setCurPercent(int percent) {
        mPercent = percent;
        new Thread(new Runnable() {
            @Override
            public void run() {
                int sleepTime = 20;
                for (int i = 0; i < mPercent; i++) {
                    if (i % 20 == 0) {
                        sleepTime += 2;
                    }
                    try {
                        Thread.sleep(sleepTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    mCurPercent = i;
                    CirclePercentView.this.postInvalidate();
                }
            }

        }).start();

    }

for (int i = 0; i < mPercent; i++)
mCurPercent = i;
    你发现了吗?就是因为在循环的时候判断条件是小于当前的mPercent,所以会造成一直比原来的值小1,更改的方法就是就是让其小于等于即可。for (int i = 0;<font color ="red">i <= mPercent</font>; i++)
    现在就可以了,还有个小问题,咦,怎么圆形中的文字没有居中呢?老规矩,上代码:

  //绘制文本
        Paint textPaint = new Paint();
        String text = mCurPercent + "%";
        textPaint.setTextSize(mCenterTextSize);
        float textLength = textPaint.measureText(text);
        textPaint.setColor(Color.WHITE);
        canvas.drawText(text, x - textLength/2, y, textPaint);

    具体的设置就是drawText了,这样其实并没有很好的做居中的适配判断,本人稍微改了下。如觉得还未居中的算法可以自己调整

        Paint textPaint = new Paint();
        String text = mCurPercent + "%";
        textPaint.setTextSize(mCenterTextSize);
        textPaint.setColor(mSmallColor);
        float textWidth = textPaint.measureText(text);
        float textHeight = (textPaint.descent() + textPaint.ascent()) / 2;
        canvas.drawText(text, mRadius - textWidth / 2, mRadius - textHeight, textPaint);

    现在看上去还算可以的了,当然如果你想更准确的话就需要更精密的计算了。
    ok,到这里效果也完成的差不多了,这个就是我在用第三方控件的时候遇到的一些问题。具体使用:

    <CirclePercentView
                android:id="@+id/rp_schedule"
                android:layout_width="80px"
                android:layout_height="80px"
                android:layout_marginTop="12px"
                //背景色
                app:bigColor="@color/textColor_disable"
                app:centerTextSize="24px"
                app:percent="0"
                //进度条的颜色
                app:smallColor="@color/selectedColor"
                app:stripeWidth="3px" />
Top