packagecom.loaderman.customviewdemo;importandroid.animation.ValueAnimator;importandroid.content.Context;importandroid.graphics.Bitmap;importandroid.graphics.BitmapFactory;importandroid.graphics.Canvas;importandroid.graphics.Color;importandroid.graphics.Matrix;importandroid.graphics.Paint;importandroid.graphics.Path;importandroid.graphics.PathMeasure;importandroid.util.AttributeSet;importandroid.view.View;public class GetPosTanView extendsView {privatePath mCirclePath, mDstPath;privatePaint mPaint;privatePathMeasure mPathMeasure;privateFloat mCurAnimValue;privateBitmap mArrawBmp;private float[] pos = new float[2];private float[] tan = new float[2];publicGetPosTanView(Context context, AttributeSet attrs) {super(context, attrs);
setLayerType(LAYER_TYPE_SOFTWARE,null);
mArrawBmp=BitmapFactory.decodeResource(getResources(), R.drawable.arraw);
mPaint= newPaint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(4);
mPaint.setColor(Color.BLACK);
mDstPath= newPath();
mCirclePath= newPath();
mCirclePath.addCircle(100, 100, 50, Path.Direction.CW);
mPathMeasure= new PathMeasure(mCirclePath, true);//true计算的path的闭合长度,false则测量当前path状态长度
ValueAnimator animator= ValueAnimator.ofFloat(0, 1);
animator.setRepeatCount(ValueAnimator.INFINITE);//无限循环
animator.addUpdateListener(newValueAnimator.AnimatorUpdateListener() {public voidonAnimationUpdate(ValueAnimator animation) {
mCurAnimValue=(Float) animation.getAnimatedValue();
invalidate();
}
});
animator.setDuration(2000);
animator.start();
}
@Overrideprotected voidonDraw(Canvas canvas) {super.onDraw(canvas);
canvas.drawColor(Color.WHITE);float length = mPathMeasure.getLength(); //计算路径长度
float stop = length *mCurAnimValue;
mDstPath.reset();
mPathMeasure.getSegment(0, stop, mDstPath, true);
canvas.drawPath(mDstPath, mPaint);/*** 箭头旋转、位移实现方式一:*/
//计算方位角//mPathMeasure.getPosTan(stop, pos, tan);//float degrees = (float) (Math.atan2(tan[1], tan[0]) * 180.0 / Math.PI);//Matrix matrix = new Matrix();//matrix.postRotate(degrees, mArrawBmp.getWidth() / 2, mArrawBmp.getHeight() / 2);//matrix.postTranslate(pos[0] - mArrawBmp.getWidth() / 2, pos[1] - mArrawBmp.getHeight() / 2);
/*** 箭头旋转、位移实现方式一:*/Matrix matrix= newMatrix();
mPathMeasure.getMatrix(stop, matrix, PathMeasure.POSITION_MATRIX_FLAG|PathMeasure.TANGENT_MATRIX_FLAG);
matrix.preTranslate(-mArrawBmp.getWidth() / 2, -mArrawBmp.getHeight() / 2);
canvas.drawBitmap(mArrawBmp, matrix, mPaint);
}
}