2. 使用线性渐变实现进度条
2021-04-26 本文已影响0人
努力生活的西鱼
前段时间,项目里面有个需求,是要实现语音包下载进度的显示。
首先看几个需要用到的东西
RectF: 根据指定坐标创建一个长方形
![](https://img.haomeiwen.com/i4175918/f8864d31ee221277.png)
LinearGradient: 线性渐变
构造函数:
public LinearGradient(float x0, float y0, float x1, float y1, @NonNull @ColorInt int colors[],
@Nullable float positions[], @NonNull TileMode tile)
- x0: 线性渐变起点的X轴坐标
- y0: 线性渐变起点的Y轴坐标
- x1: 线性渐变终点的X轴坐标
- y1: 线性渐变终点的Y轴坐标
- colors[]: 线性渐变颜色的组合
- positions[]: 取值范围为[0,1],代表上面颜色所在的位置
整体的思路就是,我们不停的设置进度值,然后不停的刷新。
/**
* 设置进度,此为线程安全控件,由于考虑多线程的问题,需要同步
* 刷新界面调用postInvalidate()能在非UI线程刷新
*
* @param progress
*/
public synchronized void setProgress(int progress) {
if (progress > mMax) {
progress = mMax;
}
this.mProgress = progress;
postInvalidate();
}
/**
* 绘制背景
*
* @param canvas
*/
private void drawBackground(Canvas canvas) {
if (mBackgroundBounds == null) {
mBackgroundBounds = new RectF();
if (mRadius == 0) {
mRadius = 52;
}
mBackgroundBounds.left = 0;
mBackgroundBounds.top = 0;
mBackgroundBounds.right = getMeasuredWidth();
mBackgroundBounds.bottom = getMeasuredHeight();
}
mPercent = mProgress / (mMax + 0f);
// 白天
mNormalColor = ContextCompat.getColor(ContextHolder.getContext(),R.color.module_setting_color_voice_normal_day);
mDownloadColor = ContextCompat.getColor(ContextHolder.getContext(),R.color.module_setting_color_voice_download_day);
// 下载从灰变蓝的渐变
linearGradient = new LinearGradient(
// 渐变起始点坐标
0, 0,
// 渐变结束点坐标
getMeasuredWidth(), 0,
// 渐变颜色数组
new int[]{mDownloadColor, mNormalColor},
// 位置数组
new float[]{mPercent, mPercent + 0.001f},
// 空白区域的填充方法
Shader.TileMode.CLAMP
);
// 从浅灰到深灰
linearGradient2 = new LinearGradient(
0,0,
getMeasuredWidth(),getMeasuredHeight(),
new int[]{Color.parseColor("#F2F2F2"),Color.parseColor("#F2F2F2")},
new float[]{0,1},
Shader.TileMode.CLAMP
);
}
mPaint.setColor(mNormalColor);
if (mPercent == 0) {
mPaint.setShader(linearGradient2);
canvas.drawRoundRect(mBackgroundBounds, mRadius, mRadius, mPaint);
} else {
mPaint.setShader(linearGradient);
canvas.drawRoundRect(mBackgroundBounds, mRadius, mRadius, mPaint);
}
}