Android自定義View——從零開始實現圓形進度條

版權聲明:本文為博主原創文章,未經博主允許不得轉載。
系列教程:Android開發之從零開始系列
源碼:github.com/AnliaLee/Progressbar,歡迎star

大家要是看到有錯誤的地方或者有啥好的建議,歡迎留言評論


前言:以前老是用別人造的輪子,知其然不知其所以然,有時看懂了別人寫的過多幾個月又忘了,遂來開個坑把一步步實現和思路寫下來,弄成一個系列。由于上班時間不多,爭取一周擼個一到兩篇出來

本篇只著重于思路和實現步驟,里面用到的一些知識原理不會非常細地拿來講,如果有不清楚的api或方法可以在網上搜下相應的資料,肯定有大神講得非常清楚的,我這就不獻丑了。本著認真負責的精神我會把相關知識的博文鏈接也貼出來(其實就是懶不想寫那么多哈哈),大家可以自行傳送

效果展示

目錄
  • 繪制一個圓弧
  • 為圓弧添加動畫效果
  • 測量及自適應圓形進度條View的寬高
  • 自定義attr屬性
  • 實現可跟隨進度條進度變化的文字效果
  • 實現進度條顏色漸變動畫

繪制一個圓弧

相關博文鏈接

【Android - 自定義View】之自定義View淺析
Android 自定義View (一)
自定義控件三部曲之繪圖篇(七)——Paint之函數大匯總

本著先寫后優化的思想,怎么簡單怎么來,像參數定義,自定義View大小適配什么的都先不去管,后面再慢慢填坑,我們就先簡單畫一個圓弧(為了更好地觀察圓弧的繪制區域,我們會將繪制圓弧的矩形區域畫出來)。代碼如下

public class CircleBarView extends View {

    private Paint rPaint;//繪制矩形的畫筆
    private Paint progressPaint;//繪制圓弧的畫筆

    public CircleBarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs);
    }

    private void init(Context context,AttributeSet attrs){
        rPaint = new Paint();
        rPaint.setStyle(Paint.Style.STROKE);//只描邊,不填充
        rPaint.setColor(Color.RED);

        progressPaint = new Paint();
        progressPaint.setStyle(Paint.Style.STROKE);//只描邊,不填充
        progressPaint.setColor(Color.BLUE);
        progressPaint.setAntiAlias(true);//設置抗鋸齒
    }

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

        float x = 50;
        float y = 50;
        RectF rectF = new RectF(x,y,x+300,y+300);//建一個大小為300 * 300的正方形區域

        canvas.drawArc(rectF,0,270,false,progressPaint);//這里角度0對應的是三點鐘方向,順時針方向遞增
        canvas.drawRect(rectF,rPaint);
    }
}

界面布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <com.anlia.progressbar.CircleBarView
            android:id="@+id/circle_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
</RelativeLayout>

在Activity中進行注冊

circleBarView = (CircleBarView)findViewById(R.id.circle_view);

效果如圖


為圓弧添加動畫效果

我們需要給圓弧的繪制加上一個動畫效果,這里主要用到Animation方面的知識,我們改下之前的CircleBarView代碼

private float sweepAngle;//圓弧經過的角度

private void init(Context context,AttributeSet attrs){
    //省略部分代碼...
    anim = new CircleAnim();
}

@Override
protected void onDraw(Canvas canvas) {
    //省略部分代碼...
    canvas.drawArc(rectF,0,sweepAngle,false,progressPaint);
}

public class CircleBarAnim extends Animation{

    public CircleBarAnim(){
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        super.applyTransformation(interpolatedTime, t);
        sweepAngle = interpolatedTime * 360;
        postInvalidate();
    }
}

//寫個方法給外部調用,用來設置動畫時間
public void setProgressNum(int time) {
    anim.setDuration(time);
    this.startAnimation(anim);
}

在Activity中調用setProgressNum()方法

circleBarView.setProgressNum(3000);//設置動畫時間為3000毫秒,即3秒

效果如圖


添加背景圓弧

根據我們最終實現的效果圖,我們還需要繪制一個完整的圓弧作為進度條圓弧的背景,同時我們需要修改一下之前的setProgressNum()方法,將當前進度條的值作為參數傳進去,以便計算進度條繪制的角度,繼續改我們之前的CircleBarView代碼

private Paint bgPaint;//繪制背景圓弧的畫筆

private float progressNum;//可以更新的進度條數值
private float maxNum;//進度條最大值

private float progressSweepAngle;//進度條圓弧掃過的角度
private float startAngle;//背景圓弧的起始角度
private float sweepAngle;//背景圓弧掃過的角度

private void init(Context context,AttributeSet attrs){
    //省略部分代碼...
    progressPaint = new Paint();
    progressPaint.setStyle(Paint.Style.STROKE);//只描邊,不填充
    progressPaint.setColor(Color.GREEN);
    progressPaint.setAntiAlias(true);//設置抗鋸齒
    progressPaint.setStrokeWidth(15);//隨便設置一個畫筆寬度,看看效果就好,之后會通過attr自定義屬性進行設置

    bgPaint = new Paint();
    bgPaint.setStyle(Paint.Style.STROKE);//只描邊,不填充
    bgPaint.setColor(Color.GRAY);
    bgPaint.setAntiAlias(true);//設置抗鋸齒
    bgPaint.setStrokeWidth(15);

    progressNum = 0;
    maxNum = 100;//也是隨便設的

    startAngle = 0;
    sweepAngle = 360;
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    //省略部分代碼...
    canvas.drawArc(rectF,startAngle,sweepAngle,false,bgPaint);
    canvas.drawArc(rectF,startAngle,progressSweepAngle,false,progressPaint);
}

public class CircleBarAnim extends Animation{

    public CircleBarAnim(){
    }
    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        super.applyTransformation(interpolatedTime, t);
        progressSweepAngle = interpolatedTime * sweepAngle * progressNum / maxNum;//這里計算進度條的比例
        postInvalidate();
    }
}

public void setProgressNum(float progressNum, int time) {
    //省略部分代碼...
    this.progressNum = progressNum;
}

在Activity中調用setProgressNum()方法

circleBarView.setProgressNum(100,3000);

效果如圖


測量及自適應圓形進度條View的寬高

相關博文鏈接

淺談自定義View的寬高獲取
教你搞定Android自定義View

在上面的代碼中,View的寬高是由繪制圓弧的矩形區域大小決定的,直接寫死在了init()方法中,而我們的實際需求是View的寬高可以由我們在外部進行設置,且無論怎么設置寬高View都應該是一個正方形(寬高相等),因此我們需要重寫View的onMeasure()方法

繼續修改我們的CircleBarView代碼

private RectF mRectF;//繪制圓弧的矩形區域

private float barWidth;//圓弧進度條寬度
private int defaultSize;//自定義View默認的寬高

private void init(Context context,AttributeSet attrs){
    //省略部分代碼...
    defaultSize = DpOrPxUtils.dip2px(context,100);
    barWidth = DpOrPxUtils.dip2px(context,10);
    mRectF = new RectF();
    
    progressPaint.setStrokeWidth(barWidth);
    
    bgPaint.setStrokeWidth(barWidth);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int height = measureSize(defaultSize, heightMeasureSpec);
    int width = measureSize(defaultSize, widthMeasureSpec);
    int min = Math.min(width, height);// 獲取View最短邊的長度
    setMeasuredDimension(min, min);// 強制改View為以最短邊為長度的正方形

    if(min >= barWidth*2){//這里簡單限制了圓弧的最大寬度
        mRectF.set(barWidth/2,barWidth/2,min-barWidth/2,min-barWidth/2);
    }

}

private int measureSize(int defaultSize,int measureSpec) {
    int result = defaultSize;
    int specMode = View.MeasureSpec.getMode(measureSpec);
    int specSize = View.MeasureSpec.getSize(measureSpec);

    if (specMode == View.MeasureSpec.EXACTLY) {
        result = specSize;
    } else if (specMode == View.MeasureSpec.AT_MOST) {
        result = Math.min(result, specSize);
    }
    return result;
}

其中用到了dp和px相互轉換的工具類(相關知識有興趣的可以自己上網搜下),這里也將相關代碼貼出來

public class DpOrPxUtils {
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
}

自定義attr屬性

相關博文鏈接

Android自定義View(二、深入解析自定義屬性)
解析:TypedArray 為什么需要調用recycle()

我們的View中有許多屬性需要在布局文件中進行設置,例如進度條顏色、寬度等等,這里我們選取最基本的五個屬性(其余的可根據需要另行擴展):進度條圓弧顏色背景圓弧顏色起始角度掃過的角度(可以理解為進度條的最大長度)、進度條寬度進行自定義

首先在res\values文件夾中添加attr.xml,為CircleBarView自定義屬性

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--注意這里的name要和自定義View的名稱一致,不然在布局文件中無法引用-->
    <declare-styleable name="CircleBarView">
        <attr name="progress_color" format="color"></attr>
        <attr name="bg_color" format="color"></attr>

        <attr name="bar_width" format="dimension"></attr>

        <attr name="start_angle" format="float"></attr>
        <attr name="sweep_angle" format="float"></attr>
    </declare-styleable>
</resources>

修改CircleBarView,為自定義屬性賦值

private int progressColor;//進度條圓弧顏色
private int bgColor;//背景圓弧顏色
private float startAngle;//背景圓弧的起始角度
private float sweepAngle;//背景圓弧掃過的角度
private float barWidth;//圓弧進度條寬度

private void init(Context context,AttributeSet attrs){
    //省略部分代碼...
    TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.CircleBarView);

    progressColor = typedArray.getColor(R.styleable.CircleBarView_progress_color,Color.GREEN);//默認為綠色
    bgColor = typedArray.getColor(R.styleable.CircleBarView_bg_color,Color.GRAY);//默認為灰色
    startAngle = typedArray.getFloat(R.styleable.CircleBarView_start_angle,0);//默認為0
    sweepAngle = typedArray.getFloat(R.styleable.CircleBarView_sweep_angle,360);//默認為360
    barWidth = typedArray.getDimension(R.styleable.CircleBarView_bar_width,DpOrPxUtils.dip2px(context,10));//默認為10dp
    typedArray.recycle();//typedArray用完之后需要回收,防止內存泄漏
  

    progressPaint.setColor(progressColor);
    progressPaint.setStrokeWidth(barWidth);
    
    bgPaint.setColor(bgColor);
    bgPaint.setStrokeWidth(barWidth);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawArc(mRectF,startAngle,sweepAngle,false,bgPaint);
    canvas.drawArc(mRectF,startAngle,progressSweepAngle,false, progressPaint);
}

在布局文件中設置自定義屬性試試效果

<!--省略部分代碼-->
<RelativeLayout 
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <com.anlia.progressbar.CircleBarView
            app:start_angle="135"
            app:sweep_angle="270"
            app:progress_color="@color/red"
            app:bg_color="@color/gray_light"
            app:bar_width="20dp"/>
    </LinearLayout>
</RelativeLayout>

效果如圖


實現可跟隨進度條進度變化的文字效果

根據需求,我們需要顯示可以跟隨進度條進度變化的文字,網上許多實現的方法都是在自定義View中實現相應的文字處理邏輯,然后使用canvas.drawText()方法去繪制文字。我個人覺得這樣寫比較麻煩且可擴展性不高,下面提供另外一種思路供大家參考

我的做法是將條形進度條和文字顯示區分開來,文字顯示的組件直接在布局文件用TextView就可以了,將TextView傳入CircleBarView,然后在CircleBarView提供接口編寫文字處理的邏輯即可。這樣實現的好處在于后期我們要是想改變文字的字體、樣式、位置等等都不需要再在CircleBarView中傷筋動骨地去改,實現了文字與進度條解耦

具體實現如下,修改我們的CircleBarView

private TextView textView;
private OnAnimationListener onAnimationListener;
public class CircleBarAnim extends Animation{
    //省略部分代碼...
    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        super.applyTransformation(interpolatedTime, t);
        //省略部分代碼...
        if(textView !=null && onAnimationListener!=null){
            textView.setText(onAnimationListener.howToChangeText(interpolatedTime,progressNum,maxNum));
        }
    }
}

/**
 * 設置顯示文字的TextView
 * @param textView
 */
public void setTextView(TextView textView) {
    this.textView = textView;
}

public interface OnAnimationListener {
    /**
     * 如何處理要顯示的文字內容
     * @param interpolatedTime 從0漸變成1,到1時結束動畫
     * @param progressNum 進度條數值
     * @param maxNum 進度條最大值
     * @return
     */
    String howToChangeText(float interpolatedTime, float progressNum, float maxNum);
}

然后在Activity中調用接口

circleBarView.setOnAnimationListener(new CircleBarView.OnAnimationListener() {
    @Override
    public String howToChangeText(float interpolatedTime, float progressNum, float maxNum) {
        DecimalFormat decimalFormat=new DecimalFormat("0.00");
        String s = decimalFormat.format(interpolatedTime * progressNum / maxNum * 100) + "%";
        return s;
    }
});
circleBarView.setProgressNum(80,3000);

布局文件也相應修改

<RelativeLayout
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="10dp">
    <com.anlia.progressbar.CircleBarView
        android:id="@+id/circle_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center_horizontal"
        app:start_angle="135"
        app:sweep_angle="270"
        app:progress_color="@color/red"
        app:bg_color="@color/gray_light"
        app:bar_width="8dp"/>
    <TextView
        android:id="@+id/text_progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>

來看下效果


其他文字效果也只需要改改布局文件就好

這里只是簡單地提供一點思路,如果大家有更復雜的需求在此基礎上擴展接口即可


實現進度條顏色漸變動畫

相關博文鏈接

Android獲得線性漸變某點的顏色

在上一點的基礎上稍微做點延伸,實現進度條的顏色漸變動畫,這里的顏色線性漸變算法由@Aaron_cxx提供,大家如果對顏色漸變算法感興趣的可以看下這位大大的博客

下面繼續改我們的CircleBarView,這里只要稍微擴展一下我們的OnAnimationListener接口即可

public interface OnAnimationListener {
    //省略部分代碼...
    /**
     * 如何處理進度條的顏色
     * @param paint 進度條畫筆
     * @param interpolatedTime 從0漸變成1,到1時結束動畫
     * @param progressNum 進度條數值
     * @param maxNum 進度條最大值
     */
    void howTiChangeProgressColor(Paint paint, float interpolatedTime, float progressNum, float maxNum);
}

//記得在我們的動畫中調用howTiChangeProgressColor
public class CircleBarAnim extends Animation{
    //省略部分代碼...
    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        super.applyTransformation(interpolatedTime, t);
        //省略部分代碼...
        onAnimationListener.howTiChangeProgressColor(progressPaint,interpolatedTime,progressNum,maxNum);
    }
}

同樣的,在Activity中編寫相應的邏輯

circleBarView.setOnAnimationListener(new CircleBarView.OnAnimationListener() {
    //省略部分代碼...
    @Override
    public void howTiChangeProgressColor(Paint paint, float interpolatedTime, float progressNum, float maxNum) {
        LinearGradientUtil linearGradientUtil = new LinearGradientUtil(Color.YELLOW,Color.RED);
        paint.setColor(linearGradientUtil.getColor(interpolatedTime));
    }
});

效果如圖

至此本篇從零開始實現的教程就告一段落了,如果大家看了感覺還不錯麻煩點個贊,你們的支持是我最大的動力~要是小伙伴們想要擴展一些新的功能,也可以在評論區給我留言,我有空會把新功能的實現教程更新上去


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,619評論 6 539
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,155評論 3 425
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,635評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,539評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,255評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,646評論 1 326
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,655評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,838評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,399評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,146評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,338評論 1 372
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,893評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,565評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,983評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,257評論 1 292
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,059評論 3 397
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,296評論 2 376

推薦閱讀更多精彩內容