如何为在Android中使用Canvas绘制的视图制作动画?

时间:2019-01-23 11:05:28

标签: android android-animation

我正在onDraw方法中使用Canvas绘制垂直步进视图。该视图是根据步骤数动态绘制的。我的看法如下 enter image description here因此,如果我当前的步骤是2,我想用在step1圈子中的颜色从圆1绘制到cirle 2的动画。然后连续发光第二个圆圈,以便引起用户的注意。如何实现这种动画效果?

1 个答案:

答案 0 :(得分:0)

为补充我的意见,以下是一种使用onDraw()ValueAnimator中逐步移动圆圈的解决方案。

class CircleWithMotion extends View implements ValueAnimator.AnimatorUpdateListener {

    private final int CIRCLE_RADIUS = 30;
    private final int STEP_Y = 200;
    private final PointF circlePosition = new PointF(100, 100);

    private ValueAnimator animator;
    private Paint paint;

    public CircleWithMotion(Context context) {
        super(context);
        paint = new Paint();
        paint.setColor(Color.BLUE);

        // HERE you can change the type and duration of the animation
        animator = new ValueAnimator();
        animator.setDuration(1000);
        animator.setInterpolator(new DecelerateInterpolator());
        animator.addUpdateListener(this);
    }

    // Call this to start the animation
    public void movingToNextStep() {
        // Sets the START and END values for the animation (FROM current y position TO next position)
        animator.setFloatValues(circlePosition.y, circlePosition.y + STEP_Y);
        animator.start();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawCircle(circlePosition.x, circlePosition.y, CIRCLE_RADIUS, paint);
    }

    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        // Update the Y circle position with the calculated value from animator
        circlePosition.y = (float) animator.getAnimatedValue();
        // say the view must be redraw
        this.invalidate();
    }
}