自定義View-NumberProgressBar

 前兩天在github上看代碼家的NumberProgressBar,看了效果,然後自己試着寫一下,可是大牛的原代碼我還沒有來得急看,我就在這裏貼一下我自己的代碼。
 效果圖如下:
這裏寫圖片描述
關於這個效果我們把View分成三段,已加載完成的,沒有加載完成的,還有就是這個字體。
 接下來看看代碼吧

1.資源文件編輯屬性

 <declare-styleable name="NumberPorgressBar">
<attr name="unreached_color" format="color|reference" />
<attr name="reached_color" format="color|reference" />
        <attr name="progress_num" format="integer" />
 <attr name="num_size" format="dimension|reference" />
        <attr name="num_color" format="color|reference" />
    </declare-styleable>

2.代碼中獲取屬性

//加載完成的粗線顯示顏色
 reachedAreaColor = array.getColor(R.styleable.NumberPorgressBar_reached_color, Color.BLACK);
 //沒有加載的粗線顯示顏色
unreachedAreaColor = array.getColor(R.styleable.NumberPorgressBar_unreached_color, Color.parseColor("#999999"));
//最開始的顯示進度
progressNum = array.getInteger(R.styleable.NumberPorgressBar_progress_num, 0);
//顯示進度的字體大小
numSize = (int) array.getDimension(R.styleable.NumberPorgressBar_num_size, 56);
//顯示進度的字體顏色
numColor = array.getColor(R.styleable.NumberPorgressBar_num_color, Color.RED);

3.onSizeChanged方法的代碼

 String progressText = "00%";
this.w = w;
textRect = new Rect();
//測量顯示進度的text的寬度
textPaint.getTextBounds(progressText, 0, progressText.length(), textRect);
//每個字體的寬度
itemWidth = (textRect.right - textRect.left) / 3;
 mWidth = w - (textRect.right - textRect.left);
segmentWidth = mWidth / 100;
mHeight = h;

4.onDraw裏面的代碼

  canvas.translate(0, mHeight / 2);
String progressText = progressNum + "%";
//已加載完畢的進度條顯示寬度
int middleWidth = progressNum * segmentWidth;
//  Log.i(Constants.TAG, "onDraw: middleWidth=" + middleWidth);
canvas.drawLine(0, 0, middleWidth, 0, reachedPaint);
//畫上顯示進度的text
 canvas.drawText(progressText, middleWidth, (textRect.bottom - textRect.top) / 2, textPaint);
if ((middleWidth + (textRect.right - textRect.left)) < mWidth && progressNum != 100){
//畫還沒有加載的到的進度條
 canvas.drawLine(middleWidth + (textRect.right - textRect.left), 0, mWidth+itemWidth, 0, unreachedPaint);}

關於加載動畫

這裏呢用的屬性動畫

 ValueAnimator animator = new ValueAnimator().ofInt(progressNum, currentProgressNum)
                .setDuration((100 - progressNum) * onePrecentTime);
        animator.setInterpolator(new LinearInterpolator());
        animator.setRepeatCount(0);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                progressNum = (int) valueAnimator.getAnimatedValue();
                invalidate();
            }
        });
        animator.start();

代碼都很容易懂,我也不多說了,原代碼在這裏:github
有不對的地方請告訴我喔,對您有幫助的話,麻煩給顆星呢。
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章