1. 程式人生 > >Android自定義View——從零開始實現圓形進度條

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

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

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

效果展示

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

繪製一個圓弧

本著先寫後優化的思想,怎麼簡單怎麼來,像引數定義,自定義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的寬高是由繪製圓弧的矩形區域大小決定的,直接寫死在了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屬性

我們的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>

來看下效果


其他文字效果也只需要改改佈局檔案就好

這裡只是簡單地提供一點思路,如果大家有更復雜的需求在此基礎上擴充套件介面即可

實現進度條顏色漸變動畫

在上一點的基礎上稍微做點延伸,實現進度條的顏色漸變動畫,這裡的顏色線性漸變演算法由@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));
    }
});

效果如圖

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