前段时间群里兄弟项目中有类似这样的需求
我看到兄弟受苦受难,于心不忍。又因事不关己,打算高高挂起。正在爱恨纠结之时,日神对我说:没事多造点轮子,你的人生会有很多收获。这波鸡汤让我深受触动,于是决定拯救兄弟于水生火热之中。
重写onMeasure 决策自身大小
显而易见当可以拖拽的范围极限为零时,也就是RangeSeeBar正常显示能够接受的极限,粗略一看:Width > 2 * Height
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (heightSize * 2 > widthSize) {
setMeasuredDimension(widthSize, widthSize / 2);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
绘制拖动条背景 凡事先从简单开始
public class RangeSeekBar extends View {
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private int lineTop, lineBottom, lineLeft, lineRight;
private int lineCorners;
private int lineWidth;
private RectF line = new RectF();
public RangeSeekBar(Context context) {
this(context, null);
}
public RangeSeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (heightSize * 2 > widthSize) {
setMeasuredDimension(widthSize, (int) (widthSize / 2));
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
int seekBarRadius = h / 2;
/**
* 属性 left right top bottom 描述了SeekBar按钮的位置
* 蓝后根据它们预先设置确定出 RectF line 背景的三维
* lineCorners 圆滑的边缘似乎会比直角更好看
*/
lineLeft = seekBarRadius;
lineRight = w - seekBarRadius;
lineTop = seekBarRadius - seekBarRadius / 4;
lineBottom = seekBarRadius + seekBarRadius / 4;
lineWidth = lineRight - lineLeft;
line.set(lineLeft, lineTop, lineRight, lineBottom);
lineCorners = (int) ((lineBottom - lineTop) * 0.45f);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setStyle(Paint.Style.FILL);
paint.setColor(0xFFD7D7D7);
canvas.drawRoundRect(line, lineCorners, lineCorners, paint);
}
}
很明显这里设计seekBarRadius作为SeekBar按钮的半径,值为RangeSeekBar自身高度一半。那么为了使默认状态的SeekBar按钮圆心能压在背景条的起点和终点
背景条的起点和终点当然就分别相对于自身宽度往内部偏移一个半径咯。