最近公司项目需求,要做一个可以动态设置所占空间多段颜色百分比的进度条,没找到合适的,需求很简单,代码也很简单,简单记录一下,直接上代码:
private Paint paint;
private int totalParts = 100; // 总共分成100份
private List<ColorsBean> colorsBeanList;
public CustomRectangleView(Context context) {
super(context);
init();
}
public CustomRectangleView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomRectangleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
paint = new Paint();
paint.setStyle(Paint.Style.FILL);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth(); // 获取View的宽度
int height = getHeight(); // 获取View的高度
// 计算每份的宽度
float partWidth = (float) width / totalParts;
// 绘制总的长方形
RectF rect = new RectF(0, 0, width, height);
//进度条背景色
paint.setColor(Color.parseColor("#f5f5f5"));
//画圆角矩形
canvas.drawRoundRect(rect, 8f,8f,paint);
// 绘制进度条色彩部分
if (colorsBeanList != null ){
for (int i = 0; i < colorsBeanList.size(); i++) {
ColorsBean bean = colorsBeanList.get(i);
paint.setColor(bean.getColor());
RectF redRect = new RectF(bean.getStart() * partWidth, 0,
bean.getEnd() * partWidth, height);
canvas.drawRect(redRect, paint);
}
}
}
// 设置进度条色彩部分的起始和结束位置
public void setSegmentPart(List<ColorsBean> colorsBeans) {
this.colorsBeanList = colorsBeans;
invalidate(); // 通知View重新绘制
}
思路:绘制一个长方形,把长方形宽度分成一百份,按照起止位置的百分比绘制颜色。
ColorsBean:
data class ColorsBean(
var start:Int,
var end:Int,
var color:Int,
)
使用:
<com.crb.card.data.view.CustomRectangleView
android:id="@+id/custom_view_progress"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_16"/>
val colorList = arrayListOf<ColorsBean>()
//设置0%-4%为蓝色
colorList.add(ColorsBean(0,4,Color.BLUE))
//设置4%-10%为蓝色
colorList.add(ColorsBean(4,10,Color.RED))
//设置10%-20%为蓝色
colorList.add(ColorsBean(10,20,Color.GREEN))
mBinding.customViewProgress.setSegmentPart(colorList)
根据以上代码可以自行添加动画效果,圆角效果等。