下載進(jìn)度條

image.png
package com.app.progressview;

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.util.AttributeSet;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

public class ProgressView extends View {
    static String MAX = "100%";
    private Paint mPaint;
    private Rect mTextBound;
    private Rect mClipBound;

    private float mTextSize;    //dp
    private int mRadius;        //px
    private int mColor;
    private float mStrokeWidth; //dp

    private int mProgress;      // progress:[0, 100]
    private float offset;       //px
    private int mTextHeight;     //px


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

    public ProgressView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

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

    void init(Context context, AttributeSet attrs) {
        float density = getResources().getDisplayMetrics().density;
        //get attrs
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ProgressView);
        mTextSize = ta.getDimension(R.styleable.ProgressView_textSize, 16 * density);
        mRadius = ta.getDimensionPixelSize(R.styleable.ProgressView_radius, 0);
        mColor = ta.getColor(R.styleable.ProgressView_color, Color.BLUE);
        mStrokeWidth = ta.getDimension(R.styleable.ProgressView_strokeWidth, 2 * density);
        Log.e("TAG", mRadius + " " + mStrokeWidth);
        ta.recycle();
        //init paint
        mPaint = new Paint();
        mPaint.setDither(true);
        mPaint.setAntiAlias(true);
        mPaint.setTextSize(mTextSize);
        mPaint.setColor(Color.BLUE);
        float strokeWidth = mStrokeWidth;
        mPaint.setStrokeWidth(strokeWidth);
        offset = strokeWidth / 2;
        //text info
        mTextBound = new Rect();
        //progress
        mClipBound = new Rect();
        Paint.FontMetricsInt fontMetricsInt = mPaint.getFontMetricsInt();
        mTextHeight = fontMetricsInt.descent + fontMetricsInt.ascent;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int width;
        int height;

        int measuredWidth = getMeasuredWidth();
        int measuredHeight = getMeasuredHeight();
        //dp,math_parent
        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthSize;
        } else if (widthMode == MeasureSpec.AT_MOST) {  //warp_content
            mPaint.getTextBounds(MAX, 0, MAX.length(), mTextBound);
            width = mTextBound.width();
        } else {
            width = 0;
        }

        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightSize;
        } else if (heightMode == MeasureSpec.AT_MOST) {
            Paint.FontMetricsInt fontMetricsInt = mPaint.getFontMetricsInt();
            int ascent = fontMetricsInt.ascent;
            int descent = fontMetricsInt.descent;
            int textHeight = descent - ascent;
            height = textHeight;
        } else {
            height = 0;
        }
        setMeasuredDimension(width, height);
    }

    String mText = "0%";

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        int startX;
        int startY;
        mText = mProgress + "%";
        int progress = (int) (width * mProgress / 100.0f);
        //確定分割點(diǎn)
        mClipBound.left = 0;
        mClipBound.top = 0;
        mClipBound.right = progress;
        mClipBound.bottom = height;

        //把文本繪制到中間位置
        //獲取文本信息绍弟,確定起點(diǎn)x坐標(biāo)
        mPaint.getTextBounds(mText, 0, mText.length(), mTextBound);
        startX = (width - mTextBound.width()) / 2;

        //獲取文本信息痴颊,確定起點(diǎn)y坐標(biāo)
        startY = (height - mTextHeight) / 2;

        mPaint.setStyle(Paint.Style.FILL);

        //draw left part
        canvas.save();
        canvas.clipRect(mClipBound);
        mPaint.setColor(mColor);
        canvas.drawRoundRect(0, 0, width, height, mRadius, mRadius, mPaint);
        mPaint.setColor(Color.WHITE);
        canvas.drawText(mText, startX, startY, mPaint);
        canvas.restore();

        mClipBound.left = progress;
        mClipBound.top = 0;
        mClipBound.right = width;
        mClipBound.bottom = height;

        //draw right part
        canvas.save();
        canvas.clipRect(mClipBound);
        mPaint.setColor(Color.WHITE);
        canvas.drawRoundRect(0, 0, width, height, mRadius, mRadius, mPaint);
        mPaint.setColor(mColor);
        canvas.drawText(mText, startX, startY, mPaint);
        canvas.restore();

        //draw outline
        mPaint.setStyle(Paint.Style.STROKE);
        canvas.drawRoundRect(0 + offset, 0 + offset, width - offset, height - offset, mRadius, mRadius, mPaint);

    }

    //progress:[0,100]
    public void setmProgress(int mProgress) {
        if (mProgress >= 0 && mProgress <= 100) {
            this.mProgress = mProgress;
            invalidate();
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ProgressView">
        <attr name="textSize" format="reference|dimension" />
        <attr name="color" format="reference|color" />
        <attr name="radius" format="reference|dimension" />
        <attr name="strokeWidth" format="reference|dimension" />
    </declare-styleable>
</resources>
package com.app.progressview;

import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private ProgressView mProgressView;
    int progress = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mProgressView = findViewById(R.id.progressView);
        findViewById(R.id.start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onStartClick();
            }
        });

    }

    private void onStartClick() {
        final Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if (progress >= 100) {
                    timer.cancel();
                    return;
                }
                progress++;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mProgressView.setmProgress(progress);
                    }
                });
            }
        };
        timer.schedule(task, 0, 60);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末饱狂,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子拙友,更是在濱河造成了極大的恐慌杠巡,老刑警劉巖派歌,帶你破解...
    沈念sama閱讀 210,978評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件床估,死亡現(xiàn)場離奇詭異含滴,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)丐巫,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,954評論 2 384
  • 文/潘曉璐 我一進(jìn)店門谈况,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人递胧,你說我怎么就攤上這事碑韵。” “怎么了缎脾?”我有些...
    開封第一講書人閱讀 156,623評論 0 345
  • 文/不壞的土叔 我叫張陵泼诱,是天一觀的道長。 經(jīng)常有香客問我赊锚,道長,這世上最難降的妖魔是什么屉栓? 我笑而不...
    開封第一講書人閱讀 56,324評論 1 282
  • 正文 為了忘掉前任舷蒲,我火速辦了婚禮,結(jié)果婚禮上友多,老公的妹妹穿的比我還像新娘牲平。我一直安慰自己,他們只是感情好域滥,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,390評論 5 384
  • 文/花漫 我一把揭開白布纵柿。 她就那樣靜靜地躺著,像睡著了一般启绰。 火紅的嫁衣襯著肌膚如雪昂儒。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,741評論 1 289
  • 那天委可,我揣著相機(jī)與錄音渊跋,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛拾酝,可吹牛的內(nèi)容都是我干的燕少。 我是一名探鬼主播,決...
    沈念sama閱讀 38,892評論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼蒿囤,長吁一口氣:“原來是場噩夢啊……” “哼客们!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起材诽,我...
    開封第一講書人閱讀 37,655評論 0 266
  • 序言:老撾萬榮一對情侶失蹤底挫,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后岳守,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體凄敢,經(jīng)...
    沈念sama閱讀 44,104評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,451評論 2 325
  • 正文 我和宋清朗相戀三年湿痢,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了涝缝。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,569評論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡譬重,死狀恐怖拒逮,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情臀规,我是刑警寧澤滩援,帶...
    沈念sama閱讀 34,254評論 4 328
  • 正文 年R本政府宣布,位于F島的核電站塔嬉,受9級特大地震影響玩徊,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜谨究,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,834評論 3 312
  • 文/蒙蒙 一恩袱、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧胶哲,春花似錦畔塔、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,725評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至寄摆,卻和暖如春谅辣,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背婶恼。 一陣腳步聲響...
    開封第一講書人閱讀 31,950評論 1 264
  • 我被黑心中介騙來泰國打工屈藐, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留榔组,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,260評論 2 360
  • 正文 我出身青樓联逻,卻偏偏與公主長得像搓扯,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子包归,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,446評論 2 348