How to animate a path on canvas - android

前端 未结 3 1369
醉酒成梦
醉酒成梦 2020-11-28 05:19

Is possible to attach an animator to a path? Is there any other way to draw on canvas animated lines? I searched this before i post , but there is nothing about this. In two

3条回答
  •  自闭症患者
    2020-11-28 05:27

    You can create a PathMeasure for your path and determine the length of it:

    private PathMeasure pathMeasure; // field
    
    // After you've created your path
    pathMeasure = new PathMeasure(path, false); 
    pathLength = pathMeasure.getLength();
    

    You can then get get a specific point on the path using getPosTan() inside, say, a ValueAnimator's update listener:

    final float[] position = new float[2]; // field
    
    // Inside your animation's update method, where dt is your 0..1 animated fraction
    final float distance = dt * pathLength;
    pathMeasure.getPosTan(distance, position, null);
    
    // If using onDraw you'll need to tell the view to redraw using the new position
    invalidate(); 
    

    You can then make use of the position in onDraw (or whatever).

    canvas.drawCircle(position[0], position[1], radius, paint);
    

    The advantages of this approach is that it is straightforward, doesn't require chunky maths, and works on all APIs.

    If using API 21+, you can use a ValueAnimator and pass in a Path to use its positions, which is simpler. Example SO question.

提交回复
热议问题