仿魅族應用商店下載進度控制元件

Mr_凌宇發表於2018-03-20

前言

因為本人是個魅族控,魅族的UI以及頁面風格真的是深入我心,特別是一些小動效更是讓我愛不釋手,所以也想仿著來做一點,好吧,囉嗦畢了,看下實現的UI效果。 這個是魅族應用商店下載進度條的進度讀取,我挺喜歡這個效果的,具體效果我們分成3部分:

  1. 沒開始之前顯示 圓角按鈕
  2. 點選下載後有一個縮回去的動畫,縮成一個圓,然後進行進度條載入
  3. 進度條走到底之後再次橫向拉,拉成一個圓角按鈕,上面顯示安裝或者是開啟。

下圖看下具體的實現效果

很醜的實現效果

gayHub地址:https://github.com/LinHuanTanLy/CircularProgressBar.git

實現過程

需求分析

先動腦再動手。 很明顯這裡面涉及到了畫弧形畫圓角矩形畫字屬性動畫,這些單獨拆出來問題不大,合併在一起就麻煩點了。 思路:

  1. 先畫矩形
  2. 點選 矩形回收,縮到一定倍數後不再畫矩形,改而畫進度條(雖然是叫進度條,但是我們不考慮用progressbar也不考慮畫圓,我們畫弧形來實現) 3.根據進度來選擇畫多少弧度的弧形,當到達360弧度的時候,即進度100%,這個時候不再畫弧形,改而畫圓角矩形,橫向拉伸到圓角矩形的寬度。

具體動手

定義需要的引數

    //    定義 寬 高 半徑 開始角度 滑動角度
    private int mW, mH, mRadius, mStartAngle = 0, mSweepAngle = 0;
    //    預設弧形的顏色,進度條顏色,暫停槓槓的顏色,字型顏色
    private int mDefColor, mProgressColor, mTabColor, mFontColor;
    //   畫進度弧度,畫中間暫停斜槓,畫預設弧度,畫文字
    private Paint mPaintForCircle, mPaintForTag, mPaintForDefCircle, mPaintForText;
    //   是否畫進度條
    private boolean isDrawProgressBar = false;
    //   由圓形進度條 進化到  圓角矩形 需要增長的半徑的倍數以及最大倍數
    private final float sMultiple = 1f, sMaxMultiple = 2.5f;
    //   可變的倍數
    private float mMultiple = sMaxMultiple;
    //   進度條的寬度,圓角矩形的寬度
    private float mStrokeWidthCircle = 12, mRectWidth = 6;
    //   圓角矩形中的提示文字
    private String mTipsStr = "下載", mTipsInstallStr = "安裝";
    //   圓角矩形中的提示文字字號大小
    private float mTipsStrFontSize = 40;
    //   下載監聽
    private OnProgressListener mOnProgressListener;
複製程式碼

重寫onDraw()

  @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.translate(mW / 2, mH / 2);
        if (isDrawProgressBar) {
            drawPauseTag(canvas);
            drawDefCircle(canvas);
            drawBigCircle(canvas);
        } else {
            drawRoundRect(canvas);
        }
    }
複製程式碼

這裡我們根據isDrawProgressBar來判斷是畫什麼圖形,相對應的方法如下:

/**
     * 畫中間的暫停按鈕
     *
     * @param canvas
     */
    private void drawPauseTag(Canvas canvas) {
        mPaintForTag.setColor(mTabColor);
        RectF rectFLeft = new RectF(-mRadius / 2.6f, -mRadius / 2.4f, -mRadius / 8, mRadius / 2.4f);
        RectF rectFRight = new RectF(mRadius / 8, -mRadius / 2.4f, mRadius / 2.6f, mRadius / 2.4f);
        canvas.drawRect(rectFLeft, mPaintForTag);
        canvas.drawRect(rectFRight, mPaintForTag);
    }
複製程式碼
 /**
     * 畫基礎的背景圓
     *
     * @param canvas
     */
    private void drawDefCircle(Canvas canvas) {
        mPaintForDefCircle.setStrokeWidth(mStrokeWidthCircle);
        mPaintForDefCircle.setColor(mDefColor);
        RectF rectF = new RectF(-mRadius, -mRadius, mRadius, mRadius);
        canvas.drawArc(rectF, mStartAngle, 360, false, mPaintForDefCircle);
    }
複製程式碼
  /**
     * 畫進度弧形
     *
     * @param canvas
     */
    private void drawBigCircle(Canvas canvas) {
        mPaintForCircle.setColor(mProgressColor);
        mPaintForCircle.setStrokeWidth(mStrokeWidthCircle);
        RectF rectF = new RectF(-mRadius, -mRadius, mRadius, mRadius);
        canvas.drawArc(rectF, mStartAngle, mSweepAngle, false, mPaintForCircle);
    }

複製程式碼
 /**
     * 畫圓角矩形
     *
     * @param canvas
     */
    private void drawRoundRect(Canvas canvas) {
        mPaintForCircle.setStrokeWidth(mRectWidth);
        mPaintForCircle.setColor(mProgressColor);
        RectF rectF = new RectF(-mRadius * mMultiple, -mRadius, mRadius * mMultiple, mRadius);
        canvas.drawRoundRect(rectF, 60, 60, mPaintForCircle);
        mPaintForCircle.setStrokeWidth(mStrokeWidthCircle);
        if (mMultiple == sMaxMultiple) {
            drawTipsText(rectF, canvas);
        }
    }

複製程式碼

這時候基本的模板已經畫好了,怎麼讓他動起來呢?我們考慮使用屬性動畫

屬性動畫

 /**
     * 用屬性動畫繪製元件  開始畫圓角矩形
     */
    private void doDrawRect() {
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(sMultiple, sMaxMultiple);
        valueAnimator.setDuration(500);
        valueAnimator.addUpdateListener(animation -> {
            mMultiple = (float) animation.getAnimatedValue();
            invalidate();
        });
        valueAnimator.start();
    }

    /**
     * 用屬性動畫繪製元件  開始畫進度條
     */
    private void doDrawProgress() {
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(sMaxMultiple, sMultiple);
        valueAnimator.setDuration(500);
        valueAnimator.addUpdateListener(animation -> {
            float rate = (float) animation.getAnimatedValue();
            mMultiple = rate;
            invalidate();
            if (rate == sMultiple) {
                isDrawProgressBar = true;
                invalidate();
            }
        });
        valueAnimator.start();
    }
複製程式碼

設定文字

自定義View寫文字一向是讓人討厭的,因為baseline實在是不好找(也可能是我太笨),這裡是在一個限定好的圓角矩形裡面寫文字,所以相對比較好處理一些:

  /**
     * 畫矩形框中的文字
     *
     * @param rectF
     * @param canvas
     */
    private void drawTipsText(RectF rectF, Canvas canvas) {
        mPaintForText.setTextSize(mTipsStrFontSize);
        mPaintForText.setColor(mFontColor);
        Paint.FontMetricsInt fontMetrics = mPaintForText.getFontMetricsInt();
        float baseline2 = rectF.bottom - ((rectF.bottom - rectF.top - fontMetrics.bottom + fontMetrics.top) / 2 + fontMetrics.bottom);
        canvas.drawText(mTipsStr, rectF.centerX(), baseline2, mPaintForText);
    }
複製程式碼

自定義屬性

  1. value/attrs.xml 定義屬性檔案:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="circular">
        <!--預設弧度的顏色-->
        <attr name="defColor" format="color"/>
        <!--進度條顏色-->
        <attr name="progressColor" format="color"/>
        <!--暫停槓槓的顏色-->
        <attr name="tabColor" format="color"/>
        <!--字型顏色-->
        <attr name="fontColor" format="color"/>
        <!--提示文字-->
        <attr name="tipsStr" format="string"/>
        <!--進度完成後的提示文字-->
        <attr name="finishStr" format="string"/>
        <!--字型大小-->
        <attr name="fontSize" format="dimension"/>
        <!--圓角矩形的寬度-->
        <attr name="rectWidth" format="dimension"/>
        <!--進度條寬度-->
        <attr name="progressWidth" format="dimension"/>
    </declare-styleable>
</resources>
複製程式碼
  1. 構造方法中獲取屬性檔案
 private void init(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.circular);
        mDefColor = typedArray.getColor(R.styleable.circular_defColor, Color.parseColor("#9E9E9E"));
        mProgressColor = typedArray.getColor(R.styleable.circular_progressColor, Color.parseColor("#FF34A350"));
        mTabColor = typedArray.getColor(R.styleable.circular_tabColor, Color.parseColor("#FF34A350"));
        mFontColor = typedArray.getColor(R.styleable.circular_fontColor, Color.parseColor("#FF34A350"));
        mTipsStr = typedArray.getString(R.styleable.circular_tipsStr);
        mStrokeWidthCircle = typedArray.getDimension(R.styleable.circular_progressWidth, 12);
        mRectWidth = typedArray.getDimension(R.styleable.circular_rectWidth, 6);
        if (TextUtils.isEmpty(mTipsStr)) {
            mTipsStr = "下載";
        }
        mTipsInstallStr = typedArray.getString(R.styleable.circular_finishStr);
        if (TextUtils.isEmpty(mTipsInstallStr)) {
            mTipsInstallStr = "安裝";
        }
        mTipsStrFontSize = typedArray.getDimension(R.styleable.circular_fontSize, 40);
        typedArray.recycle();

        mPaintForCircle = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaintForCircle.setStyle(Paint.Style.STROKE);
        mPaintForTag = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaintForDefCircle = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaintForDefCircle.setStyle(Paint.Style.STROKE);
        mPaintForText = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaintForText.setTextAlign(Paint.Align.CENTER);
    }

複製程式碼

暴露更新進度的方法供外界呼叫:

  /**
     * 是不是正在顯示進度中
     *
     * @return
     */
    public boolean isInProgress() {
        return isDrawProgressBar;
    }

    /**
     * 開始顯示下載進度
     */
    public void doStartProgress() {
        doDrawProgress();
    }

    /**
     * 暫停下載進度
     */
    public void doPauseProgress() {
        isDrawProgressBar = false;
        doDrawRect();
    }

    /**
     * 完成下載進度
     */
    public void doFinishProgress() {
        mSweepAngle = 360;
        isDrawProgressBar = false;
        mTipsStr = mTipsInstallStr;
        doDrawRect();
        if (mOnProgressListener != null) {
            mOnProgressListener.onProgressFinish();
            mSweepAngle = 0;
        }
    }


    /**
     * 更新進度
     *
     * @param curProgress 當前進度
     * @param maxProgress 全部進度
     */
    public void setProgress(int curProgress, int maxProgress) {
        if (curProgress < maxProgress) {
            BigDecimal result = new BigDecimal(curProgress).divide(new BigDecimal(maxProgress), 2, BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal(360));
            mSweepAngle = result.intValue();
        } else {
            mSweepAngle = 360;
        }
        invalidate();
    }


    /**
     * 預設弧形的顏色
     *
     * @param colorRgb
     */
    public void setDefColor(int colorRgb) {
        mDefColor = colorRgb;
    }

    /**
     * 進度條顏色
     *
     * @param colorRgb
     */
    public void setProgressColor(int colorRgb) {
        mProgressColor = colorRgb;
    }

    /**
     * 暫停槓槓的顏色
     *
     * @param colorRgb
     */
    public void setTabColor(int colorRgb) {
        mTabColor = colorRgb;
    }

    /**
     * 設定進度條寬度
     *
     * @param progressWidth
     */
    public void setProgressWidth(int progressWidth) {
        mStrokeWidthCircle = (float) progressWidth;
    }

    /**
     * 設定圓角矩形的寬度
     *
     * @param rectWidth
     */
    public void setRectWidth(int rectWidth) {
        mRectWidth = rectWidth;
    }

    /**
     * 設定矩形方框裡面的資訊文字
     *
     * @param msg
     */
    public void setTipsMessage(String msg) {
        mTipsStr = msg;
    }


    /**
     * 設定進度走完後顯示的資訊
     *
     * @param msg
     */
    public void setTipsFinish(String msg) {
        mTipsInstallStr = msg;
    }

    /**
     * 設定字型大小
     *
     * @param fontSize
     */
    public void setTipsMessageSize(int fontSize) {
        mTipsStrFontSize = fontSize;
    }

    /**
     * 設定字型顏色
     *
     * @param colorRgb
     */
    public void setFontColor(int colorRgb) {
        mFontColor = colorRgb;
    }


    /**
     * 監聽回撥
     *
     * @param onProgressListener
     */
    public void setOnProgressListener(OnProgressListener onProgressListener) {
        mOnProgressListener = onProgressListener;
    }

    public interface OnProgressListener {
        void onProgressFinish();
    }
複製程式碼

使用方法:

  1. xml定義:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="@dimen/padding_10">


    <ImageView
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:src="@mipmap/icon"/>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginLeft="@dimen/margin_20"
        android:layout_weight="1"
        android:gravity="center_vertical"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="QQ華夏手遊"
            android:textColor="@android:color/black"
            android:textSize="@dimen/fonts_18"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/margin_4"
            android:text="11.8MB"
            android:textColor="@android:color/black"
            android:textSize="@dimen/fonts_12"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/margin_4"
            android:text="3000px 超高清體驗"
            android:textColor="@android:color/black"
            android:textSize="@dimen/fonts_12"/>
    </LinearLayout>

    <com.playingjoy.fanrabbit.widget.CircularProgressBar
        android:id="@+id/cpb_test_progress"
        android:layout_width="80dp"
        android:layout_height="40dp"
        android:layout_gravity="center"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:defColor="@color/x_red"
        app:finishStr="@string/app_name"
        app:rectWidth="@dimen/margin_2"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</LinearLayout>
複製程式碼
  1. java 定義
public class TestActivity extends RxActivity {
    private CircularProgressBar mCircularProgressBar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);


        mCircularProgressBar = findViewById(R.id.cpb_test_progress);
//        mCircularProgressBar.setTipsMessage("下載");
//        mCircularProgressBar.setDefColor(getResources().getColor(R.color.x_red));
//        mCircularProgressBar.setFontColor(getResources().getColor(R.color.x_yellow));
//        mCircularProgressBar.setTabColor(getResources().getColor(R.color.x_blue));
//        mCircularProgressBar.setProgressColor(getResources().getColor(R.color.colorPrimaryDark));
//        mCircularProgressBar.setProgressWidth(4);
//        mCircularProgressBar.setRectWidth(1);
//        mCircularProgressBar.setTipsFinish("Ly");
        mCircularProgressBar.setOnClickListener(v -> {
            if (mCircularProgressBar.isInProgress()) {
                mCircularProgressBar.doPauseProgress();
            } else {
                doStartDownLoad();
            }
        });
    }

    private void doStartDownLoad() {
        mCircularProgressBar.doStartProgress();
        io.reactivex.disposables.Disposable disposable = io.reactivex.Observable.interval(1, TimeUnit.SECONDS)
                .compose(bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    XLog.e("the progress is " + aLong + 1);
                    if (aLong >= 9) {
                        mCircularProgressBar.doFinishProgress();
                    } else {
                        mCircularProgressBar.setProgress((int) ((aLong + 1) * 10), 100);
                    }
                });
        mCircularProgressBar.setOnProgressListener(disposable::dispose);

    }
}

複製程式碼

OK,基本就完成了

問題

因為本人也是自定義View初學者,所以很多問題我也不是很清楚是不是會造成問題或者是效能損耗:

  1. 這樣畫多個圖形來完成頁面會不會有效能損耗?
  2. 我這邊定義了mPaintForCircle, mPaintForTag, mPaintForDefCircle, mPaintForText四隻畫筆來完成繪圖,會不會太多了呢?是一個圖形對應一個畫筆還是可以複用呢?

相關文章