Android自定義view圓形百分比progressBar√

前言

最近工作太不飽和,基本是這個(gè)節(jié)奏:
8.40到公司,吃個(gè)早餐,邊吃邊玩手機(jī)
9.消化一下,打開(kāi)電腦看會(huì)新聞。****(這一段被屏蔽了,印度和香港問(wèn)題不能寫?),哎,我大清太難了
9.30-10.帶薪拉屎時(shí)間
10.如果當(dāng)天有茅臺(tái)搶購(gòu),也是要打開(kāi)京東搶一搶的,雖然東哥暫時(shí)還不認(rèn)我這個(gè)兄弟
11.要開(kāi)始做點(diǎn)事了(反正不是工作的事)
12.-1.30吃飯、午覺(jué)
14.把每個(gè)群的消息瀏覽一遍,最活躍的群非同學(xué)們的炒股群莫屬(每天如此),都在討論牛市要來(lái)了,準(zhǔn)備進(jìn)場(chǎng)一把梭哈。我也想試試,但是奈何錢不夠,今天還要交房租。
15.要開(kāi)始做點(diǎn)事了(一般是逛知乎、寫博客)
16.下半場(chǎng)休息時(shí)間,這個(gè)時(shí)候一般抽根黃鶴樓斗斗地主,豆子很快就會(huì)輸完,好在我有兩個(gè)號(hào),想騙我充值、看廣告,不存在的
17.繼續(xù)做“事”
18.準(zhǔn)點(diǎn)下班(怪不好意思的)

h5、小程序開(kāi)發(fā)倒是挺忙的,過(guò)幾天要正兒八經(jīng)學(xué)一下小程序,希望能一起幫前端的兄弟一起迭代之前的小程序。
現(xiàn)在呢,時(shí)間總不能浪費(fèi),寫寫blog吧,記錄一下,說(shuō)不定還能幫到需要的朋友。

進(jìn)入正題,繼續(xù)接著上一篇android自定義view實(shí)現(xiàn)進(jìn)度條動(dòng)畫、按鈕漸變及錄制狀態(tài)控制
,趁熱打鐵,繼續(xù)來(lái)畫個(gè)進(jìn)度條,這個(gè)跟上一篇實(shí)現(xiàn)方式類似,多了一個(gè)百分比數(shù)字顯示以及完成后的√。

上效果:

在這里插入圖片描述

沒(méi)什么好解釋的,直接上代碼:

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.Nullable;

/**
 * 進(jìn)度
 *
 * @author ly
 * date 2020/3/3 11:02
 */
public class CircleProgressView extends View {

    private static final int COMPLETE = 360;
    private int okSpeed = 3;

    private Paint paint;
    //進(jìn)度圈顏色
    private int circleOutsideColor;
    //進(jìn)度顏色
    private int circleProgressColor;
    private float progressW;
    //進(jìn)度條圓圈半徑
    private float circleProgressR;
    private OnProgressListener onProgressListener;

    private RectF progressRect;
    private float progress;
    private String progressText;
    private Path okPath;
    private int sX, sY;
    private int mX;
    private int eX;
    private int cX, cY;

    public CircleProgressView(Context context) {
        super(context);
        init();
    }

    public CircleProgressView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CircleProgressView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        circleOutsideColor = 0xffF2F4F5;
        circleProgressColor = 0xff6066DD;
        paint = new Paint();
        paint.setAntiAlias(true);//抗鋸齒
        paint.setDither(true); //設(shè)置防抖動(dòng)
    }

    /**
     * @param progress 已加載進(jìn)度/總進(jìn)度
     * @author ly on 2020/3/3 16:41
     */
    public void setProgress(float progress) {
        this.progress = progress * COMPLETE;
        if (this.progress >= COMPLETE) {//表示錄制達(dá)到最大時(shí)長(zhǎng),自動(dòng)結(jié)束
            this.progress = COMPLETE;
        }
        progressText = (int) (progress * 100) + "%";
        invalidate();
    }

    public void reset() {
        setProgress(0);

    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (circleProgressR == 0 || okPath == null) {
            int w = getWidth();
            progressW = w * 0.061f;
            circleProgressR = (w - progressW) / 2f;

            progressRect = new RectF(0 + progressW / 2, 0 + progressW / 2, w - progressW / 2, w - progressW / 2);

            int okW = (int) ((getWidth() - progressW) * 0.45);
            int okH = (int) ((getHeight() - progressW) * 0.32);

            cX = sX = (getWidth() - okW) / 2;
            cY = sY = getHeight() / 2;
            mX = (int) (sX + 0.39 * okW);
            int mY = (int) (sY + 0.35 * okW);
            eX = getWidth() - (getWidth() - okW) / 2;
            int eY = (getHeight() - okH) / 2;

            okPath = new Path();
            okPath.moveTo(sX, sY);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //畫進(jìn)度圈
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(circleOutsideColor);
        paint.setStrokeWidth(progressW);//設(shè)置畫筆粗細(xì)
        canvas.drawCircle(getWidth() / 2f, getHeight() / 2f, circleProgressR, paint);

        //畫進(jìn)度就是圓弧
        //時(shí)鐘3點(diǎn)的方向?yàn)?度,順時(shí)鐘方向?yàn)檎?90是圓弧的開(kāi)始點(diǎn),即12點(diǎn)位置開(kāi)始,
        //sweepAngle掃過(guò)的角度,調(diào)整該值即可實(shí)現(xiàn)進(jìn)度順時(shí)針加載(0-360)
        paint.setColor(circleProgressColor);
        canvas.drawArc(progressRect, -90, progress, false, paint);

        if (progress < COMPLETE) {
            if (!TextUtils.isEmpty(progressText)) {
                // 將坐標(biāo)原點(diǎn)移到控件中心
                int dx = getWidth() / 2;
                int dy = getHeight() / 2;
                canvas.translate(dx, dy);
                // 繪制居中文字
                paint.setTextSize(PixelUtil.sp2px(30));
                // 文字寬
                float textWidth = paint.measureText(progressText);
                // 文字baseline在y軸方向的位置
                float baseLineY = Math.abs(paint.ascent() + paint.descent()) / 2;
                paint.setStyle(Paint.Style.FILL);
//            paint.setStrokeWidth(2);
                canvas.drawText(progressText, -textWidth / 2, baseLineY, paint);
            }
        } else {//加載完成,畫√
            if (cX < eX) {//來(lái)個(gè)動(dòng)畫湊合用
                cX += okSpeed;
                if (cX < mX) {
                    cY += okSpeed;
                } else {
                    cY -= okSpeed;
                }
                invalidate();
            } else {
                postDelayed(() -> {
                    if (onProgressListener != null)
                        onProgressListener.complete();
                }, 1500);
            }
            okPath.lineTo(cX, cY);
            canvas.drawPath(okPath, paint);
        }
    }

    public float getProgress() {
        return progress / COMPLETE;
    }

    public void setOnProgressListener(OnProgressListener onProgressListener) {
        this.onProgressListener = onProgressListener;
    }

    public interface OnProgressListener {
        void complete();
    }
}

還是說(shuō)一下那個(gè)√的動(dòng)畫吧,其實(shí)是個(gè)規(guī)則的圖形,都是直線。x軸的坐標(biāo)是增加的,y坐標(biāo)先遞減再遞增。由于要畫的√的兩條直線可拆分為兩個(gè)等腰三角形對(duì)應(yīng)的斜邊,所以x和y坐標(biāo)的增減量(okSpeed)都相等。這里有兩個(gè)優(yōu)化點(diǎn):
1、okSpeed的值是固定的,可添加插值器來(lái)改變okSpeed的值,從而達(dá)到畫√的速率
2、這個(gè)√的開(kāi)始和結(jié)束的兩端是直角,略生硬,可優(yōu)化成圓角(畫筆設(shè)置paint.setStrokeCap(Paint.Cap.ROUND)即可)
其他沒(méi)什么好說(shuō)的,上dialog的代碼:

import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;

/**
 * @author ly
 * date 2019/8/1 17:36
 */
public class CircleProgressDialog extends BaseDialog {

    private CircleProgressView circleProgressView;
    private TextView tv_dialog_progress_status;
    private ImageView iv_dialog_progress_close;
    private OnProgressCallBack onProgressCallBack;

    public CircleProgressDialog(@NonNull Context context, OnProgressCallBack onProgressCallBack) {
        super(context);
        this.onProgressCallBack = onProgressCallBack;

    }

    @Override
    public int getLayoutResId() {
        return R.layout.v_dialog_circle_progress;
    }

    @Override
    public void initViews() {
        if (getWindow() != null) {
            getWindow().getAttributes().width = ScreenUtil.getScreenWidth() * 4 / 5;
            getWindow().setGravity(Gravity.CENTER);
        }
        setCanceledOnTouchOutside(false);
        setCancelable(false);

        circleProgressView = findViewById(R.id.circleProgressView);
        tv_dialog_progress_status = findViewById(R.id.tv_dialog_progress_status);
        iv_dialog_progress_close = findViewById(R.id.iv_dialog_progress_close);
        iv_dialog_progress_close.setOnClickListener(v -> {
            if (onProgressCallBack != null)
                onProgressCallBack.intoNextPage();
            dismiss();
        });
        iv_dialog_progress_close.setVisibility(View.GONE);

        circleProgressView.setOnProgressListener(() -> {
            if (onProgressCallBack != null)
                onProgressCallBack.intoNextPage();
            dismiss();
        });
        setOnDismissListener(dialog -> circleProgressView.reset());
    }

    public void setProgress(float progress) {
        circleProgressView.setProgress(progress);
        if (progress >= 1) {
            tv_dialog_progress_status.setText("發(fā)布成功");
            iv_dialog_progress_close.setVisibility(View.VISIBLE);
        } else {
            tv_dialog_progress_status.setText("正在發(fā)布中...");
            iv_dialog_progress_close.setVisibility(View.GONE);
        }
    }

    public float getProgress() {
        return circleProgressView.getProgress();
    }

    public interface OnProgressCallBack {
        void intoNextPage();
    }
}

v_dialog_circle_progress:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="@drawable/shape_white_r16"
    android:padding="12dp">

    <ImageView
        android:id="@+id/iv_dialog_progress_close"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:src="@mipmap/ico_close4dialog" />


    <com.xxx.CircleProgressView
        android:id="@+id/circleProgressView"
        android:layout_width="117dp"
        android:layout_height="117dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="34dp" />

    <TextView
        android:id="@+id/tv_dialog_progress_status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/circleProgressView"
        android:layout_centerHorizontal="true"
        android:paddingTop="23dp"
        android:paddingBottom="28dp"
        android:textColor="#ff727a7c"
        android:textSize="15sp"
        tools:text="正在發(fā)布中..." />
</RelativeLayout>

最后給個(gè)fake進(jìn)度,就可以看到效果啦:

   private ScheduledFuture<?> scheduledFuture;
   private void fakeProgress() {
        CircleProgressDialog circleProgressDialog = new CircleProgressDialog(this, () -> {});
        circleProgressDialog.show();
        scheduledFuture = ExecutorServiceManager.get().getExecutorService().scheduleWithFixedDelay(() -> {
            runOnUiThread(() -> {
                float progress = circleProgressDialog.getProgress();
                if (!circleProgressDialog.isShowing() || videoNoteInfo != null) {
                    if (scheduledFuture != null)
                        scheduledFuture.cancel(true);
                    scheduledFuture = null;
                    return;
                }
                progress += 0.006f;
                circleProgressDialog.setProgress(progress);
            });
        }, 0, 20, TimeUnit.MILLISECONDS);
    }

如果對(duì)大家有幫助,請(qǐng)點(diǎn)個(gè)贊以鼓勵(lì)我不斷前進(jìn)~

end

最后編輯于
?著作權(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ù)。

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