上次写了一篇Android 自定义View实现环形带刻度的进度条,这篇文章就简单了,只是在原来的基础上加一个颜色渐变。
按照惯例,我们先来看看效果图
一、概述
1、相比于上篇文章,这里我们的颜色渐变主要是用到Shader类,通过Paint.setShader(shader)方法为画笔Paint设置shader,这样就可以绘制出多彩的图形。那么Shader是什么呢?
Shader类是Android在图形变换中非常重要的一个类。Shader是着色器的意思,其作用是来给图像着色。
它有五个子类,每个子类都实现了Shader。
- BitmapShader
- ComposeShader
- LinearGradient
- RadialGradient
- SweepGradient
2、LinearGradient
在这里我们用LinearGradient创建线性渐变效果,其有两个构造函数:
LinearGradient(float x0, float y0, float x1, float y1, int color0, int color1, Shader.TileMode tile)
LinearGradient(float x0, float y0, float x1, float y1, int[] colors, float[] positions, Shader.TileMode tile)
我们重点说一下第一个构造函数,在此基础上理解第二个构造函数就很简单了。
LinearGradient是用来创建线性渐变效果的,它是沿着某条直线的方向渐变的,坐标(x0,y0)就是这条渐变直线的起点,坐标(x1,y1)就是这条渐变直线的终点。需要说明的是,坐标(x0,y0)和坐标(x1,y1)都是Canvas绘图坐标系中的坐标。color0和color1分别表示了渐变的起始颜色和终止颜色。LinearGradient支持TileMode,有以下三个取值:CLAMP 、REPEAT 和 MIRROR。
我们主要是添加这段代码,如下所示:
if (useGradient) {
LinearGradient gradient = new LinearGradient(0, 0, w, h, foreEndColcor, foreStartColor, Shader.TileMode.CLAMP);
mArcPaint.setShader(gradient);
} else {
mArcPaint.setColor(mArcColor);
}
二、按照流程我们就开始来看看代码啦
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" />
<!-- 进度条的前景色 起始颜色-->
<attr name="foreStartColor" format="color" />
<!-- 进度条的前景色 结束颜色-->
<attr name="foreEndColor" format="color" />
<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" />
<attr name="foreStartColor" />
<attr name="foreEndColor" />
</declare-styleable>
</resources>
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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#29292F">
<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:bgArcColor="@android:color/darker_gray"
app:foreStartColor="#FE6615"
app:foreEndColor="#F4F200"
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="目标100KM"
app:unitColor="@android:color/darker_gray"
app:unitSize="15dp"
app:value="75"
app:valueColor="#FFCC1E"
app:valueSize="80dp" />
</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.LinearGradient;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.Shader;
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;
//是否使用渐变
protected boolean useGradient=true;
//前景色起始颜色
private int foreStartColor;
//前景色结束颜色
private int foreEndColcor;
protected int mWidth;
protected int mHeight;
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);
foreStartColor = typedArray.getColor(R.styleable.CircleProgressBar_foreStartColor, Color.BLUE);
foreEndColcor = typedArray.getColor(R.styleable.CircleProgressBar_foreEndColor, Color.BLUE);
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);
if (useGradient) {
LinearGradient gradient = new LinearGradient(0, 0, w, h, foreEndColcor, foreStartColor, Shader.TileMode.CLAMP);
mArcPaint.setShader(gradient);
} else {
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";
}
}
4、在MainActivity中,点击按钮随机改变当前值
package per.lijuan.circleprogress;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import java.util.Random;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private CircleProgress mCircleProgress;
private Random mRandom;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCircleProgress = (CircleProgress) findViewById(R.id.circle_progress);
mCircleProgress.setOnClickListener(this);
mRandom = new Random();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.circle_progress:
mCircleProgress.setValue(mRandom.nextFloat() * mCircleProgress.getMaxValue());
break;
}
}
}
好了,本篇文章就这样了,存在不足的地方还望指导,感谢_