好久没有写博客了,这个就作为2016年的第一篇吧,最近一直在研究View的自定义和动画,以下是仿着手机上的一个loading做的小练习,小圆环绕着圆环的路径转动,性能方面没有过多考虑,以后还是要多多学习。
public class RollBallView extends View { private Paint mPaint; private float radius = 10f;//小圆半径 private float arcRadius = 200f;//大圆半径 private float[] mCurrentPosition = new float[2];//使用数组来记录点的坐标 /** * 测量路径的坐标位置 */ private PathMeasure pathMeasure = null; public RollBallView(Context context) { this(context, null); } public RollBallView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RollBallView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mPaint = new Paint(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); centerX = getWidth() / 2; centerY = getHeight() / 2; //绘制圆环 mPaint.setAntiAlias(true); mPaint.setColor(Color.GRAY); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(5f); canvas.drawCircle(centerX, centerY, arcRadius, mPaint); //绘制path Path mPath = new Path(); mPath.addCircle(centerX, centerY, arcRadius, Path.Direction.CW); pathMeasure = new PathMeasure(mPath, true); canvas.drawPath(mPath, mPaint); //绘制小圆 mPaint.reset(); mPaint.setAntiAlias(true); mPaint.setColor(Color.BLUE); canvas.drawCircle(mCurrentPosition[0], mCurrentPosition[1], radius, mPaint); } private ValueAnimator valueAnimator; private float centerX; private float centerY; // 开启路径动画 public void startPathAnim() { valueAnimator = ValueAnimator.ofFloat(0, pathMeasure.getLength()); valueAnimator.setDuration(3000);//时间 valueAnimator.setRepeatCount(-1);//无限循环 // 插值器 valueAnimator.setInterpolator(new LinearInterpolator()); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float value = (Float) animation.getAnimatedValue(); // 获取当前点坐标封装到mCurrentPosition pathMeasure.getPosTan(value, mCurrentPosition, null); postInvalidate(); } }); valueAnimator.start(); } // 关闭路径动画 public void stopPathAnim() { if (valueAnimator.isRunning()) { valueAnimator.cancel(); } } }源代码下载路径: http://download.csdn.net/detail/u011886064/9400584