Android自定义View——从零开始实现圆形进度条
2017-10-12 12:26
651 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。
系列教程:Android开发之从零开始系列
源码:github.com/AnliaLee/Progressbar,欢迎star
大家要是看到有错误的地方或者有啥好的建议,欢迎留言评论
前言:以前老是用别人造的轮子,知其然不知其所以然,有时看懂了别人写的过多几个月又忘了,遂来开个坑把一步步实现和思路写下来,弄成一个系列。由于上班时间不多,争取一周撸个一到两篇出来
本篇只着重于思路和实现步骤,里面用到的一些知识原理不会非常细地拿来讲,如果有不清楚的api或方法可以在网上搜下相应的资料,肯定有大神讲得非常清楚的,我这就不献丑了。本着认真负责的精神我会把相关知识的博文链接也贴出来(其实就是懒不想写那么多哈哈),大家可以自行传送
效果展示
目录
绘制一个圆弧
为圆弧添加动画效果
测量及自适应圆形进度条View的宽高
自定义attr属性
实现可跟随进度条进度变化的文字效果
实现进度条颜色渐变动画
【Android - 自定义View】之自定义View浅析
Android 自定义View (一)
自定义控件三部曲之绘图篇(七)——Paint之函数大汇总
本着先写后优化的思想,怎么简单怎么来,像参数定义,自定义View大小适配什么的都先不去管,后面再慢慢填坑,我们就先简单画一个圆弧(为了更好地观察圆弧的绘制区域,我们会将绘制圆弧的矩形区域画出来)。代码如下
界面布局:
在Activity中进行注册
效果如图
在Activity中调用setProgressNum()方法
效果如图
12032
作为进度条圆弧的背景,同时我们需要修改一下之前的setProgressNum()方法,将当前进度条的值作为参数传进去,以便计算进度条绘制的角度,继续改我们之前的CircleBarView代码
在Activity中调用setProgressNum()方法
效果如图
浅谈自定义View的宽高获取
教你搞定Android自定义View
在上面的代码中,View的宽高是由绘制圆弧的矩形区域大小决定的,直接写死在了init()方法中,而我们的实际需求是View的宽高可以由我们在外部进行设置,且无论怎么设置宽高View都应该是一个正方形(宽高相等),因此我们需要重写View的onMeasure()方法
继续修改我们的CircleBarView代码
其中用到了dp和px相互转换的工具类(相关知识有兴趣的可以自己上网搜下),这里也将相关代码贴出来
Android自定义View(二、深入解析自定义属性)
解析:TypedArray 为什么需要调用recycle()
我们的View中有许多属性需要在布局文件中进行设置,例如进度条颜色、宽度等等,这里我们选取最基本的五个属性(其余的可根据需要另行扩展):进度条圆弧颜色、背景圆弧颜色、起始角度、扫过的角度(可以理解为进度条的最大长度)、进度条宽度进行自定义
首先在res\values文件夹中添加attr.xml,为CircleBarView自定义属性
修改CircleBarView,为自定义属性赋值
在布局文件中设置自定义属性试试效果
效果如图
我的做法是将条形进度条和文字显示区分开来,文字显示的组件直接在布局文件用TextView就可以了,将TextView传入CircleBarView,然后在CircleBarView提供接口编写文字处理的逻辑即可。这样实现的好处在于后期我们要是想改变文字的字体、样式、位置等等都不需要再在CircleBarView中伤筋动骨地去改,实现了文字与进度条解耦
具体实现如下,修改我们的CircleBarView
然后在Activity中调用接口
布局文件也相应修改
来看下效果
其他文字效果也只需要改改布局文件就好
这里只是简单地提供一点思路,如果大家有更复杂的需求在此基础上扩展接口即可
Android获得线性渐变某点的颜色
在上一点的基础上稍微做点延伸,实现进度条的颜色渐变动画,这里的颜色线性渐变算法由@Aaron_cxx提供,大家如果对颜色渐变算法感兴趣的可以看下这位大大的博客
下面继续改我们的CircleBarView,这里只要稍微扩展一下我们的OnAnimationListener接口即可
同样的,在Activity中编写相应的逻辑
效果如图
至此本篇从零开始实现的教程就告一段落了,如果大家看了感觉还不错麻烦点个赞,你们的支持是我最大的动力~要是小伙伴们想要扩展一些新的功能,也可以在评论区给我留言,我有空会把新功能的实现教程更新上去
系列教程: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秒
效果如图
添加背景圆弧
根据我们最终实现的效果图,我们还需要绘制一个完整的圆弧12032
作为进度条圆弧的背景,同时我们需要修改一下之前的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)); } });
效果如图
至此本篇从零开始实现的教程就告一段落了,如果大家看了感觉还不错麻烦点个赞,你们的支持是我最大的动力~要是小伙伴们想要扩展一些新的功能,也可以在评论区给我留言,我有空会把新功能的实现教程更新上去
相关文章推荐
- Android自定义View-绘制扇形实现圆形进度
- Android自定义View实现带百分比圆形进度条
- 自定义View实现Android圆形进度条
- 自定义View实现Android圆形进度条,支持自定义显示的样式
- Android自定义View——从零开始实现水波浪进度框
- Android:自定义View实现绚丽的圆形进度条
- Android编程基于自定义View实现绚丽的圆形进度条功能示例
- Android 自定义View实现圆形进度条 深入理解onDraw和onMeasure及自定义属性
- Android自定义View实现音频播放圆形进度条
- Android自定义View之实现环形进度条
- Android 自定义View,自定义属性--自定义圆形进度条(整理)
- Android 高手进阶之自定义View,自定义属性(带进度的圆形进度条)
- Android 高手进阶之自定义View,自定义属性(带进度的圆形进度条)
- Android 高手进阶之自定义View,自定义属性(带进度的圆形进度条)
- Android 自定义View修炼-仿360手机卫士波浪球进度的实现
- 自定义实现圆形播放进度条(android,飞一般的感觉)
- Android自定义控件之圆形进度条ImageView
- Android 高手进阶之自定义View,自定义属性(带进度的圆形进度条)
- Android 高手进阶之自定义View,自定义属性(带进度的圆形进度条)
- Android 高手进阶之自定义View,自定义属性(带进度的圆形进度条)