帶百分比的進(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)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容