先看看效果图
小箭头绕着圆不断的改变角度进行旋转
下面直接贴代码吧 有详细的注释
public class PathMeasureView extends View
{
private Paint mPaint = new Paint();
private Paint mLinePaint = new Paint();
private Bitmap mBitmap;
private int width, height;
private float aFloat = 0f;
public PathMeasureView(Context context)
{
this(context, null);
}
public PathMeasureView(Context context, AttributeSet attrs)
{
this(context, attrs, 0);
}
public PathMeasureView(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(Color.BLACK);
mPaint.setStrokeWidth(4);
mLinePaint.setStyle(Paint.Style.STROKE);
mLinePaint.setColor(Color.RED);
mLinePaint.setStrokeWidth(6);
//得到图片资源
BitmapFactory.Options options = new BitmapFactory.Options();
//载入缩略图 载入的缩略图是原图大小的1/4。
options.inSampleSize = 4;
mBitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.arrow, options);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//得到该控件的宽高
width = MeasureSpec.getSize(widthMeasureSpec);
height = MeasureSpec.getSize(heightMeasureSpec);
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
if (aFloat >= 1)
{
aFloat = 0;
} else
{
aFloat += 0.01;
}
canvas.drawLine(width / 2, 0, width / 2, height, mLinePaint);
canvas.drawLine(0, height / 2, width, height / 2, mLinePaint);
canvas.translate(getWidth() / 2, getHeight() / 2);
//绘制一个圆
Path path = new Path();
path.addCircle(0, 0, 200, Path.Direction.CW);
canvas.drawPath(path, mPaint);
//创建一个PathMeasure
PathMeasure pathMeasure = new PathMeasure(path, false);
//使用 pathMeasure.getPosTan() 得到圆的起点的 坐标 以及该点的切线与x轴的正切值
//float distance, float pos[], float tan[]
//distance 传入距离path绘制起点的距离 这里我们传入0
//float pos[] 该点的x,y坐标
//float tan[] 该点的切线与x轴的夹角的正切值 其中tan0是邻边边长,tan1是对边边长
pathMeasure.getPosTan(pathMeasure.getLength() * aFloat, pos, tan);
//根据tan值 知道了两条边 可以求出这点切线的角度
double degree = (Math.atan2(tan[1], tan[0]) * 180.0 / Math.PI);
//绘制图片到该点上去
Matrix matrix = new Matrix();
matrix.reset();
//旋转角度 旋转中心为 图片的中心点
matrix.postRotate((float) degree, mBitmap.getWidth() / 2, mBitmap.getHeight() / 2);
//将图片的绘制点中心与当前点重合
matrix.postTranslate(pos[0] - mBitmap.getWidth() / 2, pos[1] - mBitmap.getHeight() / 2);
canvas.drawBitmap(mBitmap, matrix, mPaint);
invalidate();
}
private float[] pos = new float[2];
private float[] tan = new float[2];
}