重铸安卓荣光——双向滑块增强

时间:2024-03-01 17:18:33
public class CustomRangeSlider extends RangeSlider { private Paint paint; public CustomRangeSlider(Context context) { super(context); init(); } public CustomRangeSlider(Context context, AttributeSet attrs) { super(context, attrs); init(); } public CustomRangeSlider(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { paint = new Paint(); paint.setColor(Color.BLACK); paint.setStrokeWidth(2); } @Override protected synchronized void onDraw(Canvas canvas) { int tickCount = 11; // 刻度线的数量 setPadding((int) UiUtils.dp2px(getContext(),15),0,(int) UiUtils.dp2px(getContext(),15),0); float trackWidth = getWidth() - getPaddingStart() - getPaddingEnd(); float tickSpacing = trackWidth / (tickCount - 1); for (int i = 0; i < tickCount; i++) { float x = getPaddingStart() + i * tickSpacing; float height; if (i % 2 == 0) { height = (float) getHeight() / 2 + getThumbRadius(); String text = i * 10 + "%"; paint.setTextSize(UiUtils.dp2px(getContext(),13)); // 设置文字大小 float textWidth = paint.measureText(text); // 计算文字宽度 canvas.drawText(text, x - textWidth / 2,getHeight(), paint); // 绘制文字在刻度线底部 }else { height = (float) getHeight() / 2 + (float) getThumbRadius() / 2; } canvas.drawLine(x, (float) getHeight() /2, x, height, paint); } super.onDraw(canvas); } }