帶百分比的進(jìn)度條

package com.github.cai.greendaotaste.progress;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;

import com.github.cai.greendaotaste.R;

/**
 * Created by admin on 2017/6/6.
 */

public class ProgressWithPercent extends View {

    public static final String TAG = ProgressWithPercent.class.getSimpleName();

    public static final int DEFAULT_SMOOTH_FACTOR = 10;
    //為了滑動(dòng)更平滑
    private int mSmoothFactor;

    private int mProgressBackgroundColor, mProgressForegroundColor, mProgressTextColor;
    private float mProgressTextSize;
    private float mRoundRectRadius;
    private float mPaddingRightProgress;

    private int currentProgressWidth = 0, targetProgress, drawProgress = 0;
    private int mAnimationDuration, mAnimationTimeStartDelay;

    private Paint mProgressBackgroundPaint, mProgressForegroundPaint, mProgressTextPaint;
    private ValueAnimator mValueAnimator;
    private RectF mBackgroundRectF, mProgressRectF = new RectF();

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

    public ProgressWithPercent(Context context, AttributeSet attrs) {
        super(context, attrs);
        initAttr(context, attrs);
        initPaint();
        initProgressAnimation();
    }

    private void initAttr(Context context, AttributeSet attrs) {
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ProgressWithPercent);

        mProgressBackgroundColor = ta.getColor(R.styleable.ProgressWithPercent_progressBackground, Color.GRAY);
        mProgressForegroundColor = ta.getColor(R.styleable.ProgressWithPercent_progressForeground, Color.YELLOW);
        mProgressTextColor = ta.getColor(R.styleable.ProgressWithPercent_progressTextColor, Color.RED);
        mProgressTextSize = ta.getDimensionPixelSize(R.styleable.ProgressWithPercent_progressTextSize, 18);
        mPaddingRightProgress = ta.getDimensionPixelSize(R.styleable.ProgressWithPercent_progressTextPaddingToRight, 10);
        mRoundRectRadius = ta.getDimensionPixelSize(R.styleable.ProgressWithPercent_progressRoundRectRadius, 10);
        targetProgress = ta.getInt(R.styleable.ProgressWithPercent_progressTargetValue, 100);
        mAnimationDuration = ta.getInt(R.styleable.ProgressWithPercent_progressAnimationTimeDuration, 3000);
        mAnimationTimeStartDelay = ta.getInt(R.styleable.ProgressWithPercent_progressAnimationTimeStartDelay, 500);
        mSmoothFactor = ta.getInt(R.styleable.ProgressWithPercent_progressSmoothFactor, DEFAULT_SMOOTH_FACTOR);

        ta.recycle();
    }

    private void initPaint() {
        mProgressBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mProgressBackgroundPaint.setStrokeWidth(1);
        mProgressBackgroundPaint.setColor(mProgressBackgroundColor);
        mProgressBackgroundPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        mProgressBackgroundPaint.setStrokeCap(Paint.Cap.ROUND);

        mProgressForegroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mProgressForegroundPaint.setStrokeWidth(1);
        mProgressForegroundPaint.setColor(mProgressForegroundColor);
        mProgressForegroundPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        mProgressForegroundPaint.setStrokeCap(Paint.Cap.ROUND);

        mProgressTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mProgressTextPaint.setTextSize(mProgressTextSize);
        mProgressTextPaint.setColor(mProgressTextColor);
        mProgressTextPaint.setStrokeWidth(1);
        mProgressTextPaint.setStyle(Paint.Style.FILL_AND_STROKE);
    }

    public void initProgressAnimation() {
        mValueAnimator = ValueAnimator.ofInt(0, targetProgress * mSmoothFactor);
        mValueAnimator.setDuration(mAnimationDuration);
        mValueAnimator.setStartDelay(mAnimationTimeStartDelay);
        mValueAnimator.setInterpolator(new LinearInterpolator());
        mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int progress = (int) animation.getAnimatedValue();
                if (listener != null)
                    listener.progressStateChange(progress / mSmoothFactor);
                drawProgress = progress / mSmoothFactor;
                currentProgressWidth = progress * (getWidth() - getPaddingRight()) / (100 * mSmoothFactor);
                invalidate();
            }
        });
        mValueAnimator.start();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mBackgroundRectF = new RectF(getPaddingLeft(), getPaddingTop(), w - getPaddingRight(), h - getPaddingBottom());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawRoundRect(mBackgroundRectF, mRoundRectRadius, mRoundRectRadius, mProgressBackgroundPaint);
        mProgressRectF.set(getPaddingLeft(), getPaddingTop(), currentProgressWidth, getMeasuredHeight() - getPaddingBottom());
        canvas.drawRoundRect(mProgressRectF, mRoundRectRadius, mRoundRectRadius, mProgressForegroundPaint);
        String drawString = String.format("%d%s", drawProgress, "%");
        //得到文本的寬度
        float textWidth = mProgressTextPaint.measureText(drawString);
        float textX = currentProgressWidth - textWidth - mPaddingRightProgress;
        Rect textRect = new Rect();
        mProgressTextPaint.getTextBounds(drawString, 0, drawString.length() - 1, textRect);
        //加上是因?yàn)槔L制文本時(shí)是以文本底部為基線
        float textY = (getMeasuredHeight() >> 1) + (textRect.height() >> 1);
        if (textX - getPaddingLeft() > 0) {
            canvas.drawText(drawString, textX, textY, mProgressTextPaint);
        }else{
            canvas.drawText(drawString, getPaddingLeft(), textY, mProgressTextPaint);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        if (heightSpecMode == MeasureSpec.AT_MOST){
            DisplayMetrics metrics = new DisplayMetrics();
            WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
            wm.getDefaultDisplay().getMetrics(metrics);
            int wrapContentHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, metrics);
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(wrapContentHeight,MeasureSpec.EXACTLY);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    public void startProgressAnimation(){
        if (mValueAnimator.isRunning()){
            mValueAnimator.cancel();
        }
        mValueAnimator.start();
    }

    private ProgressListener listener;

    public void setListener(ProgressListener listener) {
        this.listener = listener;
    }

    interface ProgressListener {
        void progressStateChange(int progress);
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市弓叛,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖植兰,帶你破解...
    沈念sama閱讀 222,590評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件峰髓,死亡現(xiàn)場(chǎng)離奇詭異烁试,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)戏罢,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)脚囊,“玉大人龟糕,你說(shuō)我怎么就攤上這事』谠牛” “怎么了讲岁?”我有些...
    開(kāi)封第一講書人閱讀 169,301評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)衬以。 經(jīng)常有香客問(wèn)我缓艳,道長(zhǎng),這世上最難降的妖魔是什么看峻? 我笑而不...
    開(kāi)封第一講書人閱讀 60,078評(píng)論 1 300
  • 正文 為了忘掉前任阶淘,我火速辦了婚禮,結(jié)果婚禮上互妓,老公的妹妹穿的比我還像新娘溪窒。我一直安慰自己坤塞,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,082評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布澈蚌。 她就那樣靜靜地躺著摹芙,像睡著了一般。 火紅的嫁衣襯著肌膚如雪宛瞄。 梳的紋絲不亂的頭發(fā)上瘫辩,一...
    開(kāi)封第一講書人閱讀 52,682評(píng)論 1 312
  • 那天,我揣著相機(jī)與錄音坛悉,去河邊找鬼伐厌。 笑死,一個(gè)胖子當(dāng)著我的面吹牛裸影,可吹牛的內(nèi)容都是我干的挣轨。 我是一名探鬼主播,決...
    沈念sama閱讀 41,155評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼轩猩,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼卷扮!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起均践,我...
    開(kāi)封第一講書人閱讀 40,098評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤晤锹,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后彤委,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體鞭铆,經(jīng)...
    沈念sama閱讀 46,638評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,701評(píng)論 3 342
  • 正文 我和宋清朗相戀三年焦影,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了车遂。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,852評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡斯辰,死狀恐怖舶担,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情彬呻,我是刑警寧澤衣陶,帶...
    沈念sama閱讀 36,520評(píng)論 5 351
  • 正文 年R本政府宣布,位于F島的核電站闸氮,受9級(jí)特大地震影響剪况,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜湖苞,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,181評(píng)論 3 335
  • 文/蒙蒙 一拯欧、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧财骨,春花似錦镐作、人聲如沸藏姐。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 32,674評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)羔杨。三九已至,卻和暖如春杨蛋,著一層夾襖步出監(jiān)牢的瞬間兜材,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,788評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工逞力, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留曙寡,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,279評(píng)論 3 379
  • 正文 我出身青樓寇荧,卻偏偏與公主長(zhǎng)得像举庶,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子揩抡,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,851評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容