自定义View实战之
自定义水平循环滚动的ProgressBar
直接上代码,附详细注释。
public class HorizontalLoopProgressBar extends View {
private int color; //短线的颜色
private float lineWidth; //短线的宽度
private float space; //短线之间的间隔
private Paint paint; //绘制短线的画笔
private int startX; //绘制短线的起点
public HorizontalLoopProgressBar(Context context) {
this(context, null);
}
public HorizontalLoopProgressBar(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public HorizontalLoopProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.HorizontalLoopProgressBar);
if (typedArray != null) {
color = typedArray.getColor(R.styleable.HorizontalLoopProgressBar_lineColor, getResources().getColor(R.color.darkRed));
lineWidth = typedArray.getDimension(R.styleable.HorizontalLoopProgressBar_lineWidth, UiUtils.dpToPx(context, 50));
space = typedArray.getDimension(R.styleable.HorizontalLoopProgressBar_space, UiUtils.dpToPx(context, 20));
}
if (typedArray != null) {
typedArray.recycle();
}
paint = new Paint();
paint.setColor(color);
paint.setAntiAlias(true);
}
@Override
protected void onDraw(Canvas canvas) {
//整个控件的高度和宽度当执行到onDraw时已经layout了宽高早已经测量完成
int w = getMeasuredWidth();
int h = getMeasuredHeight();
//每次重绘短线移动的距离
int delta = 10;
//画笔的宽度
paint.setStrokeWidth(h);
//startX从0开始每次递增delta,当第一根短线(最右边一根)的右端到达空间末尾时从0重新开始绘制,形成循环
if (startX >= w + (lineWidth + space) - (w % (lineWidth + space))) {
startX = 0;
} else {
startX += delta;
}
float start = startX;
//绘制短线
while (start < w) {
canvas.drawLine(start, 5, start + lineWidth, 5, paint);
start += (lineWidth + space);
}
start = startX - space - lineWidth;
//从左边进入的短线
while (start >= -lineWidth) {
canvas.drawLine(start, 5, start + lineWidth, 5, paint);
start -= (lineWidth + space);
}
//延迟一定的时间重绘,否则太快了,如果要流畅的话1s至少得16帧即62ms一帧,这里设置为60还挺流畅的
// postInvalidateDelayed(30);
invalidate();
}
}