最近看到很多金融应用用一种数值选择器,一把尺子的设计,刻度可以左右滑动改变,如下图:
不多说,上代码
public class Ruler extends View {
private static final int RULER_LINE_MAX = 50;
private static final int RULER_LINE_MID = 30;
private static final int RULER_LINE_MIN = 20;
private static final int RULER_LINE_SLOT = 15;
private final int slop;
int width;
int height;
Paint mPaint;
Paint mColorPaint;
float lastX;
float moveX;
float bottom;
int current;
public Ruler(Context context) {
this(context, null);
}
public Ruler(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public Ruler(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
slop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
mPaint = new Paint();
mColorPaint = new Paint();
mColorPaint.setColor(Color.RED);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastX = event.getX();
return true;
case MotionEvent.ACTION_MOVE:
float dx = lastX - event.getX();
moveX += dx;
Log.e("----", dx + "");
lastX = event.getX();
if (moveX < 0) {
moveX = 0;
}
invalidate();
return true;
case MotionEvent.ACTION_UP:
if (moveX % RULER_LINE_SLOT == 0) {
invalidate();
return true;
}
moveX = (Math.round(moveX / RULER_LINE_SLOT)) * RULER_LINE_SLOT;
invalidate();
return true;
}
return super.onTouchEvent(event);
}
@Override
protected void onDraw(Canvas canvas) {
if (height == 0) {
width = getMeasuredWidth();
height = getMeasuredHeight();
bottom = height / 2;
}
int lineLen = 0;
boolean drawText;
for (int i = (int) (moveX / RULER_LINE_SLOT) + 1, slot = RULER_LINE_SLOT - (int) (moveX % RULER_LINE_SLOT); slot < width; i++, slot += RULER_LINE_SLOT) {
if (i % 10 == 0) {
lineLen = RULER_LINE_MAX;
drawText = true;
} else if (i % 5 == 0) {
lineLen = RULER_LINE_MID;
drawText = false;
} else {
lineLen = RULER_LINE_MIN;
drawText = false;
}
canvas.drawLine(slot, bottom, slot, bottom - lineLen, mPaint);
if (drawText) {
canvas.drawText(String.valueOf(i), slot, bottom - lineLen, mPaint);
}
if (Math.abs(slot - width / 2) < RULER_LINE_SLOT / 2) {
current = i;
}
}
canvas.drawLine(0, bottom, width, bottom, mPaint);
canvas.drawLine(width / 2, bottom, width / 2, bottom - RULER_LINE_MAX * 3 / 2, mColorPaint);
canvas.drawText(String.valueOf(current), width / 2, bottom - RULER_LINE_MAX * 3 / 2, mColorPaint);
}
}