Android 自定义View实现环形带刻度的进度条
本篇文章讲的是自定义View实现环形带刻度的进度条。和往常一样,主要还是想总结一下自定义View实现环形带刻度的进度条的开发过程以及一些需要注意的地方。
按照惯例,我们先来看看效果图
一、我们如何来实现这样一个环形刻度进度条:
首先,需要绘制一个灰色的环形刻度尺底图,来作为未填充时的进度条;
然后,根据传入的当前进度值,绘制填充时的进度圆弧;
其次,根据进度值绘制文字提示;
最后,重绘控件,加上动画,从而达到显示进度的效果。
二、view的几个常用触发方法
- onFinishInflate():当View中所有的子控件均被映射成xml后触发
- onMeasure(int widthMeasureSpec, int heightMeasureSpec):确定所有子元素的大小
- onLayout(boolean changed, int l, int t, int r, int b):当View分配所有的子元素的大小和位置时触发
- onSizeChanged(int w, int h, int oldw, int oldh):当view的大小发生变化时触发
- onDraw(Canvas canvas):负责将View绘制在屏幕上
三、View 的几个构造函数
1、public CircleProgress(Context context)
—>java代码直接new一个CircleProgress实例的时候,会调用这个只有一个参数的构造函数;
2、public CircleProgress(Context context, AttributeSet attrs)
—>在默认的XML布局文件中创建的时候调用这个有两个参数的构造函数。AttributeSet类型的参数负责把XML布局文件中所自定义的属性通过AttributeSet带入到View内;
3、public CircleProgress(Context context, AttributeSet attrs, int defStyleAttr)
—>构造函数中第三个参数是默认的Style,这里的默认的Style是指它在当前Application或者Activity所用的Theme中的默认Style,且只有在明确调用的时候才会调用
4、public CircleProgress(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
—>该构造函数是在API21的时候才添加上的
自定义View中,我们需要重写了3个构造方法,在上面的构造方法中说过默认的布局文件调用的是两个参数的构造方法,所以记得让所有的构造方法调用三个参数的构造方法,然后在三个参数的构造方法中获得自定义属性。
一开始一个参数的构造方法和两个参数的构造方法是这样的:
public CircleProgress(Context context) {
super(context);
}
public CircleProgress(Context context, AttributeSet attrs) {
super(context, attrs);
}
我们需要注意的是super应该改成this,然后让一个参数的构造方法引用两个参数的构造方法,两个参数的构造方法引用三个参数的构造方法,代码如下:
public CircleProgress(Context context) {
this(context, null);
}
public CircleProgress(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
四、下面我们就开始来看看代码啦
1、自定义View的属性,首先在res/values/ 下建立一个attrs.xml , 在里面定义我们的需要用到的属性以及声明相对应属性的取值类型
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- 是否开启抗锯齿 -->
<attr name="antiAlias" format="boolean" />
<!-- 圆弧起始角度,3点钟方向为0,顺时针递增,小于0或大于360进行取余 -->
<attr name="startAngle" format="float" />
<!-- 圆弧度数 -->
<attr name="sweepAngle" format="float" />
<!-- 设置动画时间 -->
<attr name="animTime" format="integer" />
<!-- 绘制内容的数值 -->
<attr name="maxValue" format="float" />
<attr name="value" format="float" />
<!-- 绘制内容的单位 -->
<attr name="unit" format="string|reference" />
<attr name="unitSize" format="dimension" />
<attr name="unitColor" format="color|reference" />
<!-- 绘制内容相应的提示语 -->
<attr name="hint" format="string|reference" />
<attr name="hintSize" format="dimension" />
<attr name="hintColor" format="color|reference" />
<!-- 精度,默认为0 -->
<attr name="precision" format="integer" />
<attr name="valueSize" format="dimension" />
<attr name="valueColor" format="color|reference" />
<!-- 背景圆弧颜色,默认白色 -->
<attr name="bgArcColor" format="color|reference" />
<!-- 圆弧宽度 -->
<attr name="arcWidth" format="dimension" />
<!-- 圆弧颜色, -->
<attr name="arcColors" format="color|reference" />
<!-- 文字的偏移量 相对于圆半径而言,默认三分之一 -->
<attr name="textOffsetPercentInRadius" format="float" />
<!-- 背景圆弧宽度 -->
<attr name="bgArcWidth" format="dimension" />
<!-- 线条数 -->
<attr name="dottedLineCount" format="integer" />
<!-- 圆弧跟虚线之间的距离 -->
<attr name="lineDistance" format="integer" />
<!-- 线条宽度 -->
<attr name="dottedLineWidth" format="dimension" />
<declare-styleable name="CircleProgressBar">
<attr name="antiAlias" />
<attr name="startAngle" />
<attr name="sweepAngle" />
<attr name="animTime" />
<attr name="maxValue" />
<attr name="value" />
<attr name="unit" />
<attr name="unitSize" />
<attr name="unitColor" />
<attr name="hint" />
<attr name="hintSize" />
<attr name="hintColor" />
<attr name="precision" />
<attr name="valueSize" />
<attr name="valueColor" />
<attr name="bgArcColor" />
<attr name="arcWidth" />
<attr name="arcColors" />
<attr name="textOffsetPercentInRadius" />
<attr name="bgArcWidth" />
<attr name="dottedLineCount" />
<attr name="lineDistance" />
<attr name="dottedLineWidth" />
</declare-styleable>
</resources>
format是值该属性的取值类型,format取值类型总共有10种,包括:string,color,demension,integer,enum,reference,float,boolean,fraction和flag。
2、然后在XML布局中声明我们的自定义View
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context=".MainActivity">
<per.lijuan.circleprogress.CircleProgress
android:id="@+id/circle_progress"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
app:antiAlias="true"
app:arcWidth="15dp"
app:dottedLineWidth="12dp"
app:hint="百分比"
app:bgArcColor="@android:color/darker_gray"
app:bgArcWidth="2dp"
app:hintSize="15dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.498"
app:maxValue="100"
app:startAngle="135"
app:sweepAngle="270"
app:textOffsetPercentInRadius="0.5"
app:unit="%"
app:unitSize="15dp"
app:value="75"
app:valueSize="15dp" />
</android.support.constraint.ConstraintLayout>
一定要引入xmlns:app="http://schemas.android.com/apk/res-auto",Android Studio中我们可以使用res-atuo命名空间,就不用添加自定义View全类名。
3、在View的构造方法中,获得我们的自定义的样式并绘制环形刻度进度条
package per.lijuan.circleprogress;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public class CircleProgress extends View {
private static final String TAG = CircleProgress.class.getSimpleName();
private Context mContext;
//默认大小
private int mDefaultSize;
//是否开启抗锯齿
private boolean antiAlias;
//绘制提示
private TextPaint mHintPaint;
private CharSequence mHint;
private int mHintColor;
private float mHintSize;
private float mHintOffset;
//绘制单位
private TextPaint mUnitPaint;
private CharSequence mUnit;
private int mUnitColor;
private float mUnitSize;
private float mUnitOffset;
//绘制数值
private TextPaint mValuePaint;
private float mValue;
private float mMaxValue;
private float mValueOffset;
private int mPrecision;
private String mPrecisionFormat;
private int mValueColor;
private float mValueSize;
//绘制圆弧
private Paint mArcPaint;
private float mArcWidth;
private float mStartAngle, mSweepAngle;
private RectF mRectF;
//当前进度,[0.0f,1.0f]
private float mPercent;
//动画时间
private long mAnimTime;
//属性动画
private ValueAnimator mAnimator;
//绘制背景圆弧
private Paint mBgArcPaint;
private int mBgArcColor;
private int mArcColor;
private float mBgArcWidth;
//圆心坐标,半径
private Point mCenterPoint;
private float mRadius;
private float mTextOffsetPercentInRadius;
private int mArcCenterX;
// 内部虚线的外部半径
private float mExternalDottedLineRadius;
// 内部虚线的内部半径
private float mInsideDottedLineRadius;
// 线条数
private int mDottedLineCount = 100;
// 圆弧跟虚线之间的距离
private int mLineDistance = 20;
// 线条宽度
private float mDottedLineWidth = 40;
public CircleProgress(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
mContext = context;
mDefaultSize = dipToPx(mContext, 150);
mAnimator = new ValueAnimator();
mRectF = new RectF();
mCenterPoint = new Point();
initAttrs(attrs);
initPaint();
setValue(mValue);
}
private void initAttrs(AttributeSet attrs) {
TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.CircleProgressBar);
antiAlias = typedArray.getBoolean(R.styleable.CircleProgressBar_antiAlias, true);
mHint = typedArray.getString(R.styleable.CircleProgressBar_hint);
mHintColor = typedArray.getColor(R.styleable.CircleProgressBar_hintColor, Color.BLACK);
mHintSize = typedArray.getDimension(R.styleable.CircleProgressBar_hintSize, 15);
mValue = typedArray.getFloat(R.styleable.CircleProgressBar_value, 50);
mMaxValue = typedArray.getFloat(R.styleable.CircleProgressBar_maxValue, 50);
//内容数值精度格式
mPrecision = typedArray.getInt(R.styleable.CircleProgressBar_precision, 0);
mPrecisionFormat = getPrecisionFormat(mPrecision);
mValueColor = typedArray.getColor(R.styleable.CircleProgressBar_valueColor, Color.BLACK);
mValueSize = typedArray.getDimension(R.styleable.CircleProgressBar_valueSize, 15);
mUnit = typedArray.getString(R.styleable.CircleProgressBar_unit);
mUnitColor = typedArray.getColor(R.styleable.CircleProgressBar_unitColor, Color.BLACK);
mUnitSize = typedArray.getDimension(R.styleable.CircleProgressBar_unitSize, 30);
mArcWidth = typedArray.getDimension(R.styleable.CircleProgressBar_arcWidth, 15);
mStartAngle = typedArray.getFloat(R.styleable.CircleProgressBar_startAngle, 270);
mSweepAngle = typedArray.getFloat(R.styleable.CircleProgressBar_sweepAngle, 360);
mBgArcColor = typedArray.getColor(R.styleable.CircleProgressBar_bgArcColor, Color.WHITE);
mArcColor = typedArray.getColor(R.styleable.CircleProgressBar_arcColors, Color.RED);
mBgArcWidth = typedArray.getDimension(R.styleable.CircleProgressBar_bgArcWidth, 15);
mTextOffsetPercentInRadius = typedArray.getFloat(R.styleable.CircleProgressBar_textOffsetPercentInRadius, 0.33f);
mAnimTime = typedArray.getInt(R.styleable.CircleProgressBar_animTime, 1000);
mDottedLineCount = typedArray.getInteger(R.styleable.CircleProgressBar_dottedLineCount, mDottedLineCount);
mLineDistance = typedArray.getInteger(R.styleable.CircleProgressBar_lineDistance, mLineDistance);
mDottedLineWidth = typedArray.getDimension(R.styleable.CircleProgressBar_dottedLineWidth, mDottedLineWidth);
typedArray.recycle();
}
private void initPaint() {
mHintPaint = new TextPaint();
// 设置抗锯齿,会消耗较大资源,绘制图形速度会变慢。
mHintPaint.setAntiAlias(antiAlias);
// 设置绘制文字大小
mHintPaint.setTextSize(mHintSize);
// 设置画笔颜色
mHintPaint.setColor(mHintColor);
// 从中间向两边绘制,不需要再次计算文字
mHintPaint.setTextAlign(Paint.Align.CENTER);
mValuePaint = new TextPaint();
mValuePaint.setAntiAlias(antiAlias);
mValuePaint.setTextSize(mValueSize);
mValuePaint.setColor(mValueColor);
// 设置Typeface对象,即字体风格,包括粗体,斜体以及衬线体,非衬线体等
mValuePaint.setTypeface(Typeface.DEFAULT_BOLD);
mValuePaint.setTextAlign(Paint.Align.CENTER);
mUnitPaint = new TextPaint();
mUnitPaint.setAntiAlias(antiAlias);
mUnitPaint.setTextSize(mUnitSize);
mUnitPaint.setColor(mUnitColor);
mUnitPaint.setTextAlign(Paint.Align.CENTER);
mArcPaint = new Paint();
mArcPaint.setAntiAlias(antiAlias);
// 设置画笔的样式,为FILL,FILL_OR_STROKE,或STROKE
mArcPaint.setStyle(Paint.Style.STROKE);
// 设置画笔粗细
mArcPaint.setStrokeWidth(mArcWidth);
// 当画笔样式为STROKE或FILL_OR_STROKE时,设置笔刷的图形样式,如圆形样式
// Cap.ROUND(圆形样式)或Cap.SQUARE(方形样式)
mArcPaint.setStrokeCap(Paint.Cap.ROUND);
mBgArcPaint = new Paint();
mBgArcPaint.setAntiAlias(antiAlias);
mBgArcPaint.setColor(mBgArcColor);
mBgArcPaint.setStyle(Paint.Style.STROKE);
mBgArcPaint.setStrokeWidth(mBgArcWidth);
mBgArcPaint.setStrokeCap(Paint.Cap.ROUND);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(measureView(widthMeasureSpec, mDefaultSize),
measureView(heightMeasureSpec, mDefaultSize));
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mArcCenterX = (int) (w / 2.f);
Log.d(TAG, "onSizeChanged: w = " + w + "; h = " + h + "; oldw = " + oldw + "; oldh = " + oldh);
//求圆弧和背景圆弧的最大宽度
float maxArcWidth = Math.max(mArcWidth, mBgArcWidth);
//求最小值作为实际值
int minSize = Math.min(w - getPaddingLeft() - getPaddingRight() - 2 * (int) maxArcWidth,
h - getPaddingTop() - getPaddingBottom() - 2 * (int) maxArcWidth);
//减去圆弧的宽度,否则会造成部分圆弧绘制在外围
mRadius = minSize / 2;
//获取圆的相关参数
mCenterPoint.x = w / 2;
mCenterPoint.y = h / 2;
//绘制圆弧的边界
mRectF.left = mCenterPoint.x - mRadius - maxArcWidth / 2;
mRectF.top = mCenterPoint.y - mRadius - maxArcWidth / 2;
mRectF.right = mCenterPoint.x + mRadius + maxArcWidth / 2;
mRectF.bottom = mCenterPoint.y + mRadius + maxArcWidth / 2;
//计算文字绘制时的 baseline
//由于文字的baseline、descent、ascent等属性只与textSize和typeface有关,所以此时可以直接计算
//若value、hint、unit由同一个画笔绘制或者需要动态设置文字的大小,则需要在每次更新后再次计算
mValueOffset = mCenterPoint.y + getBaselineOffsetFromY(mValuePaint);
mHintOffset = mCenterPoint.y - mRadius * mTextOffsetPercentInRadius + getBaselineOffsetFromY(mHintPaint);
mUnitOffset = mCenterPoint.y + mRadius * mTextOffsetPercentInRadius + getBaselineOffsetFromY(mUnitPaint);
mArcPaint.setColor(mArcColor);
Log.d(TAG, "onSizeChanged: 控件大小 = " + "(" + w + ", " + h + ")"
+ "圆心坐标 = " + mCenterPoint.toString()
+ ";圆半径 = " + mRadius
+ ";圆的外接矩形 = " + mRectF.toString());
// 虚线的外部半径
mExternalDottedLineRadius = (int) (mRectF.width() / 2)+mLineDistance;
// 虚线的内部半径
mInsideDottedLineRadius = mExternalDottedLineRadius - mDottedLineWidth;
}
private float getBaselineOffsetFromY(Paint paint) {
Paint.FontMetrics fontMetrics = paint.getFontMetrics();
return ((Math.abs(fontMetrics.ascent) - fontMetrics.descent))/ 2;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
drawText(canvas);
drawArc(canvas);
}
/**
* 绘制内容文字
*
* @param canvas
*/
private void drawText(Canvas canvas) {
canvas.drawText(String.format(mPrecisionFormat, mValue), mCenterPoint.x, mValueOffset, mValuePaint);
if (mHint != null) {
canvas.drawText(mHint.toString(), mCenterPoint.x, mHintOffset, mHintPaint);
}
if (mUnit != null) {
canvas.drawText(mUnit.toString(), mCenterPoint.x, mUnitOffset, mUnitPaint);
}
}
private void drawArc(Canvas canvas) {
// 绘制背景圆弧
// 从进度圆弧结束的地方开始重新绘制,优化性能
canvas.save();
// 360 * Math.PI / 180
float evenryDegrees = (float) (2.0f * Math.PI / mDottedLineCount);
float startDegress = (float) (135 * Math.PI / 180);
float endDegress = (float) (225 * Math.PI / 180);
for (int i = 0; i < mDottedLineCount; i++) {
float degrees = i * evenryDegrees;
// 过滤底部90度的弧长
if (degrees > startDegress && degrees < endDegress) {
continue;
}
float startX = mArcCenterX + (float) Math.sin(degrees) * mInsideDottedLineRadius;
float startY = mArcCenterX - (float) Math.cos(degrees) * mInsideDottedLineRadius;
float stopX = mArcCenterX + (float) Math.sin(degrees) * mExternalDottedLineRadius;
float stopY = mArcCenterX - (float) Math.cos(degrees) * mExternalDottedLineRadius;
canvas.drawLine(startX, startY, stopX, stopY, mBgArcPaint);
}
canvas.rotate(mStartAngle, mCenterPoint.x, mCenterPoint.y);
// 第一个参数 oval 为 RectF 类型,即圆弧显示区域
// startAngle 和 sweepAngle 均为 float 类型,分别表示圆弧起始角度和圆弧度数
// 3点钟方向为0度,顺时针递增
// 如果 startAngle < 0 或者 > 360,则相当于 startAngle % 360
// useCenter:如果为True时,在绘制圆弧时将圆心包括在内,通常用来绘制扇形
float currentAngle = mSweepAngle * mPercent;
canvas.drawArc(mRectF, 2, currentAngle, false, mArcPaint);
canvas.restore();
}
public boolean isAntiAlias() {
return antiAlias;
}
public CharSequence getHint() {
return mHint;
}
public void setHint(CharSequence hint) {
mHint = hint;
}
public CharSequence getUnit() {
return mUnit;
}
public void setUnit(CharSequence unit) {
mUnit = unit;
}
public float getValue() {
return mValue;
}
/**
* 设置当前值
*
* @param value
*/
public void setValue(float value) {
if (value > mMaxValue) {
value = mMaxValue;
}
float start = mPercent;
float end = value / mMaxValue;
startAnimator(start, end, mAnimTime);
}
private void startAnimator(float start, float end, long animTime) {
mAnimator = ValueAnimator.ofFloat(start, end);
mAnimator.setDuration(animTime);
mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mPercent = (float) animation.getAnimatedValue();
mValue = mPercent * mMaxValue;
if (BuildConfig.DEBUG) {
Log.d(TAG, "onAnimationUpdate: percent = " + mPercent
+ ";currentAngle = " + (mSweepAngle * mPercent)
+ ";value = " + mValue);
}
invalidate();
}
});
mAnimator.start();
}
/**
* 获取最大值
*
* @return
*/
public float getMaxValue() {
return mMaxValue;
}
/**
* 设置最大值
*
* @param maxValue
*/
public void setMaxValue(float maxValue) {
mMaxValue = maxValue;
}
/**
* 获取精度
*
* @return
*/
public int getPrecision() {
return mPrecision;
}
public void setPrecision(int precision) {
mPrecision = precision;
mPrecisionFormat = getPrecisionFormat(precision);
}
public long getAnimTime() {
return mAnimTime;
}
public void setAnimTime(long animTime) {
mAnimTime = animTime;
}
/**
* 重置
*/
public void reset() {
startAnimator(mPercent, 0.0f, 1000L);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
//释放资源
}
/**
* 测量 View
*
* @param measureSpec
* @param defaultSize View 的默认大小
* @return
*/
private static int measureView(int measureSpec, int defaultSize) {
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;
}
/**
* dip 转换成px
*
* @param dip
* @return
*/
public static int dipToPx(Context context, float dip) {
float density = context.getResources().getDisplayMetrics().density;
return (int) (dip * density + 0.5f * (dip >= 0 ? 1 : -1));
}
/**
* 获取数值精度格式化字符串
*
* @param precision
* @return
*/
public static String getPrecisionFormat(int precision) {
return "%." + precision + "f";
}
}
好了,本篇文章已经全部写完了,存在总结不到位的地方还望指导,感谢_
源码下载