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

前言

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

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

下圖看下具體的實現效果 java

很醜的實現效果

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

實現過程

需求分析

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

  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來判斷是畫什麼圖形,相對應的方法以下:git

/** * 畫中間的暫停按鈕 * * @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);
        }
    }

複製代碼

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

屬性動畫

/** * 用屬性動畫繪製組件 開始畫圓角矩形 */
    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實在是很差找(也多是我太笨),這裏是在一個限定好的圓角矩形裏面寫文字,因此相對比較好處理一些:canvas

/** * 畫矩形框中的文本 * * @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,基本就完成了app

問題

由於本人也是自定義View初學者,因此不少問題我也不是很清楚是否是會形成問題或者是性能損耗:ide

  1. 這樣畫多個圖形來完成頁面會不會有性能損耗?
  2. 我這邊定義了mPaintForCircle, mPaintForTag, mPaintForDefCircle, mPaintForText四隻畫筆來完成繪圖,會不會太多了呢?是一個圖形對應一個畫筆仍是能夠複用呢?
相關文章
相關標籤/搜索