版權聲明:本文為博主原創文章,未經博主允許不得轉載。
系列教程: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的寬高是由繪制圓弧的矩形區域大小決定的,直接寫死在了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));
}
});
效果如圖
至此本篇從零開始實現的教程就告一段落了,如果大家看了感覺還不錯麻煩點個贊,你們的支持是我最大的動力~要是小伙伴們想要擴展一些新的功能,也可以在評論區給我留言,我有空會把新功能的實現教程更新上去