自定义View加载图片—Path和ValueAnimator的练习

     好久没有写博客了,这个就作为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


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值