PathMeasure 看名字其实是计算指定路径信息得一个类。
初始化:
PathMeasure
pathMeasure.setPath(path,forceClosed);
//forceClosed表示对path路径是否闭合计算,也就是如果path没有闭合,forceClosed为true,那计算得是path闭合后得路径,但对原path没有影响。
PathMeasrue pathMeasure = new PathMeasure(path,forceClosed);
常用方法:
getLength()//计算path长度
isClosed() // 判断path是否闭合
nextContour() //跳转下一个曲线函数,顺序与path添加得顺序一致
getSegment(float startD,float stopD,Path dst,boolean startWidthMoveTo) //获取Path某个片段, startD为开始长度,stopD为结束长度,dst是截取后叠加的path,startWidthMoveTo表示起始点是否使用moveTo。使用getSegment()时候需要关闭硬件加速。这里startWidthMoveTo一般使用true,表示会调用Path.MoveTo()方法将路径起始点改为新添加的路径起始点(保持原状)。如果为false,不会调用Path.MoveTo()方法,则会将截取出来的 Path 片段的起始点移动到 dst 的最后一个点,以 保证 dst 路径的连续性。
我们可以使用getSegment()去实现类似loading的效果
ini
protected void onDraw(Canvas canvas) { super.onDraw(canvas);
float length = mPathMeasure.getLength();
float stop = length * mCurAnimValue;
float start =0
if(start>=0){
start = 2* mCurAnimaValue -1
}
mDstPath.reset();
canvas.drawColor(Color.WHITE); mPathMeasure.getSegment(start, stop, mDstPath, true);
canvas.drawPath(mDstPath, mPaint);
}
getPosTan(float distance,float[] pos,float[] tan) //用于得到路径上某一长度位置以及该位置的正切值。
disance表示距起始点的长度,pos该点的坐标值,tan该点正切值。
在使用中,我们一般得到float[] tan的返回值后,我们可以利用Math中的 atan2(double y,double x)来计算对应的角度,举例:
ini
protected void onDraw(Canvas canvas) {
...
mPathMeasure.getPosTan(distance,pos,tan);
float degree= (float)Math.atan2(tan[1],tan[0]) * 180f / Math.PI;
Matrix matrix = new Matrix();
matrix.postRotate(degree,bitmap.getWidth()/2,bitmap.getHeight()/2);
matrix.postTransLate(pos[0],pos[1]);
canvas.drawBitmap(bitmap,matrix,paint);
}
getMatrix(float distance,Matrix matrix,int flags) //这个函数用于得到路径某一长度的位置以及该位置的正切值矩阵,其中matrix会根据传入的flags存入不同得内容。 PathMasure.POSITION_MATRIX_FLAG表示获取位置信息。PathMeasure.TANGENT_MATRIX_FLAG表示获取切边信息。
有了这个方法,那上面的示例就更方便了:
scss
protected void onDraw(Canvas canvas) {
...
Matrix matrix = new Matrix();
mPathMeasure.getMatrix(distance,matrix, PathMasure.POSITION_MATRIX_FLAG|PathMeasure.TANGENT_MATRIX_FLAG);
matrix.preTranslate(-bitmap.getWidth() / 2,-bitmap.getHeight() / 2); //注意这里是pre
canvas.drawBitmap(bitmap,matrix,paint);
}