说起PathMeasure这Api可能对于大多数刚入门Android不久的开发者来说有点陌生,但是PathMeasure在我们的view中也是有着很重要的地位,他对于贝塞尔曲线(path)的测量有至关重要的作用,下面我们就来讲解下PathMeasure常用的api以及它在path中的作用:
PathMeasure类中持有Path对象的引用,在利用pathMesure对path进行相关操作的时候,首先要队path进行初始化;在本类中提供了两个初始化的方法:
1、通过构造方法进行初始化
public PathMeasure(Path path, boolean forceClosed) {
// The native implementation does not copy the path, prevent it from being GC'd
mPath = path;
native_instance = native_create(path != null ? path.readOnlyNI() : 0,
forceClosed);
}
第一个参数是path, 第二个参数代表是否对路径进行闭合测量(path的起点和终点是否闭合的这部分是否参与测量),true代表是,false代表否;
如果path路径是一个圆形,那么true和false是一样的效果,因为圆形本身就是一个闭合的曲线;
2、通过setPath()方法进行初始化
public void setPath(Path path, boolean forceClosed) {
mPath = path;
native_setPath(native_instance,
path != null ? path.readOnlyNI() : 0,
forceClosed);
}
这里的path和forceClosed两个参数,和第一种方法代表的意思是一样的;
path对象初始化完成后,接下来就要使用pathMeasure提供的方法,对成员path进行操作;
第一个方法:
public boolean getPosTan(float distance, float pos[], float tan[]) {
if (pos != null && pos.length < 2 ||
tan != null && tan.length < 2) {
throw new ArrayIndexOutOfBoundsException();
}
return native_getPosTan(native_instance, distance, pos, tan);
}
distance代表path曲线中的目标点距离path起点的长度;
pos[] 浮点型数组,存放着目标点在画布中x,y方向的坐标值;
tan[] 浮点型数组,存放目标点在曲线上的方向信息,通过它可以获取到目标点的切线方向与X轴的夹角;
tan[0]表示目标点切线夹角在单位圆中临边的长度 tan[1]表示目标点切线夹角在单位圆中对边的长度;
根据Math.atan2(tan[1],tan[0])*180/Math.PI;可以算出当前点的切线与X轴的角度;
此方法可以在path的圆形路径中,获取到每个点的在单位圆中与X轴的夹角,就可以对当前点的目标进行对应角度的旋转操作;
第二个方法:
public boolean getMatrix(float distance, Matrix matrix, int flags) {
return native_getMatrix(native_instance, distance, matrix.native_instance, flags);
}
distance 距离path起点的长度;
matrix 将当前点的信息存放再martix里面
flags 表示存放信息的类型,有两个值
public static final int POSITION_MATRIX_FLAG = 0x01; 表示位置信息(坐标值);
public static final int TANGENT_MATRIX_FLAG = 0x02; 表示当前点在曲线上的方向;
此方法可以在path的圆形路径中,将目标点的信心存放在matrix对象中,就可以根据matrix对当前点的目标进行对应角度的旋转操作;
第三个方法:
public boolean getSegment(float startD, float stopD, Path dst, boolean startWithMoveTo) {
// Skia used to enforce this as part of it's API, but has since relaxed that restriction
// so to maintain consistency in our API we enforce the preconditions here.
float length = getLength();
if (startD < 0) {
startD = 0;
}
if (stopD > length) {
stopD = length;
}
if (startD >= stopD) {
return false;
}
return native_getSegment(native_instance, startD, stopD, dst.mutateNI(), startWithMoveTo);
}
startD :开始截取位置距离path起点的长度
stopD: 结束截取的位置距离path起点的长度
dst: 将截取的path保存在dst中
startWithMoveTO:表示起始点是否用moveto进行移动,用于保证path截取的第一个点位置不变;
第四个方法:
public boolean nextContour() {
return native_nextContour(native_instance);
}
此方发表示从当前的path路径跳到下一个path路径
比如
:Path mPath = new Path()
PathMeasure pathMeasere = new PathMeasure (mPath,true);
int first = pathMeasure.getLength();
pathMeasure.nextContour();
int second = pathMeasure.getLength();
这个时候就可以获取到path中两个不同路径的长度;
好了到这里pathMeasure类中几个重要的方法就介绍完了,后期会更新在实际项目中具体的使用