构造方法分为
PathMeasure()
这个构造方法的产生的对象可以用setPath来与path进行关联
PathMeasure(Path path, boolean forceClosed)
其中forceClosed 设置path是否闭合,本身不会对path产生影响
但是对计算结果会有影响
getLength()
获取绘制路径的长度
isClosed()
判断path是否是闭合的
如果 构造PathMeasure的时候设置forceClosed 为true 那isClosed返回的结果肯定为true
通过 getPosTan做一个图片沿着 圆球转圈的操作
在init中对图片做一下缩放
val options =BitmapFactory.Options()
options.inSampleSize=4
mBitmap= BitmapFactory.decodeResource(resources, R.mipmap.arrow,options)
先定义一个类变量
var degree=0f
话画一个xy的坐标轴 交叉点为手机中心,然后把画布的起始坐标移到手机中心处
canvas.drawLine(width/2f,0f,width/2f,height.toFloat(),mLinePaint)
canvas.drawLine(0f,height/2f,width.toFloat(),height/2f,mLinePaint)
canvas.translate(width/2f,height/2f)
val mPath = Path()
mPath.reset()
画一个0,0 为圆心 200为半径的远
mPath.addCircle(0f,0f,200f,Path.Direction.CW)
canvas.drawPath(mPath,mPaint)
然后再ondraw方法中进行循环递增作为图片旋转的角度系数 0到1
degree+=0.01f
if(degree>=1){
degree=0f
}
通过pathMeasure的length 获取 当前点的角度和位置
数组pos 保存当前点的坐标
数组tan保存的是当前点对圆做切线切线的与X轴的正切值
pathMeasure.getPosTan(pathMeasure.length*degree,pos,tan )
//计算当前切线与x轴的夹角的度数
val degrees =Math.atan2(tan[1].toDouble(), tan[0] .toDouble())*180/Math.PI
mMatrix.reset()
//进行角度旋转 在图片转的时候 保证箭头方向和切线方向一致
mMatrix.postRotate(degrees.toFloat(), mBitmap.width / 2.toFloat(), mBitmap.height / 2.toFloat());
//将图片的绘制点中心与当前点重合 这个的意思就是 把图片贴在当前点的坐标上上进行移动,因为图片坐标轴是左上角0,0 所以
//很难和圆边缘重合, 减去 一半的宽 和一半的高 就能保证 图片中心和当前点的坐标重合
mMatrix.postTranslate(pos[0] - mBitmap!!.width / 2, pos[1]-mBitmap.height / 2)
canvas.drawBitmap(mBitmap,mMatrix, mPaint);
另一种方法 用的getMatrix
val pathMeasure = PathMeasure(mPath,false)
//将pos信息和tan信息保存在mMatrix中
pathMeasure.getMatrix(
pathMeasure.length * degree,
mMatrix,
PathMeasure.POSITION_MATRIX_FLAG or PathMeasure.TANGENT_MATRIX_FLAG
)
//将图片的旋转坐标调整到图片中心位置
mMatrix.preTranslate((-mBitmap.width/2).toFloat(),(-mBitmap.height/2).toFloat())
canvas.drawBitmap(mBitmap,mMatrix,mPaint)