话不多说 上效果图
其实这两种本质上都是一样的,只是水平和竖直的区别,我也是借鉴了别的大佬的代码写的,原文章是刻度尺的,原文地址:(353条消息) 自定义view之刻度尺_拍码屁的博客-CSDN博客
第一步呢,也是跟原文章一样的步骤,定义好View的属性,在values文件夹下面创建一个attrs.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="Ruler">
<attr name="interval" format="dimension"/>
<attr name="fromValue" format="integer"/>
<attr name="toValue" format="integer"/>
<attr name="currentValue" format="integer"/>
<attr name="intervalsBetweenValues" format="integer"/>
<attr name="valuesInterval" format="integer"/>
<attr name="valuesTextSize" format="dimension"/>
<attr name="valuesTextColor" format="color"/>
<attr name="linesWidth" format="dimension"/>
<attr name="linesColor" format="color"/>
<attr name="isShowPointer" format="boolean"/>
<attr name="orientation">
<enum name="vertical" value="0"/>
<enum name="horizontal" value="1"/>
</attr>
</declare-styleable>
</resources>
第二步呢,就是开始写我们的自定义View啦:
水平的自定义View的Java文件如下:
/**
* Created by Eve on 2022/9/30.
*/
public class RulerView extends View {
//两刻度之间的距离
private int interval;
//起始值
private int fromValue = 0;
//结束值
private int toValue = 300;
//两刻度之间的单位
private int intervalsBetweenValues = 1;
//两刻度的差值
private int valuesInterval = 1;
//当前值
private int currentValue;
private Paint paint;
private int currentPosition;
private int offset;
private int oldX;
private OnMoveActionListener mMove = null;
public RulerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray array=context.obtainStyledAttributes(attrs, R.styleable.Ruler);
interval=array.getDimensionPixelSize(R.styleable.Ruler_interval, dp2px(intervalsBetweenValues));
currentValue=array.getInt(R.styleable.Ruler_currentValue, (fromValue+toValue)/2);
array.recycle();
paint=new Paint();
//当前所指的刻度位置,即指示针指向的值
currentPosition=currentValue/valuesInterval*intervalsBetweenValues;
}
public RulerView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RulerView(Context context) {
this(context, null);
}
public static int dp2px(float dpValue) {
return (int) (0.5f + dpValue * Resources.getSystem().get