How to make svg animation with Animated in react-native

前端 未结 3 1424
栀梦
栀梦 2021-02-01 09:29

ReactNative:


    
        

        
相关标签:
3条回答
  • 2021-02-01 10:00

    No better answers, and I implemented by adding listener to Animated.Value variable, you can get more info from my question description.

    0 讨论(0)
  • 2021-02-01 10:07

    Use setNativeProps for Much Better Performance.

    I did some more tinkering and found a more performant method that makes use of addListener and setNativeProps.

    Constructor

    constructor(props) {
      super(props);
    
      this.state = { circleRadius: new Animated.Value(50) };
    
      this.state.circleRadius.addListener( (circleRadius) => {
        this._myCircle.setNativeProps({ r: circleRadius.value.toString() });
      });
    
      setTimeout( () => {
        Animated.spring( this.state.circleRadius, { toValue: 100, friction: 3 } ).start();
      }, 2000)
    }
    

    Render

    render() {
      return(
        <Svg height="400" width="400">
          <AnimatedCircle ref={ ref => this._myCircle = ref } cx="250" cy="250" r="50" fill="black" />
        </Svg>
      )
    }
    

    Result

    And this is what the animation looks like when the 2 second (2000 millisecond) timeout triggers.

    circle animation with setnativeprops

    So, the main thing you needed to change was using setNativeProps instead of using setState in your listener. This makes a native call and bypasses re-calculating the entire component, which in my case was very complex and slow to do.

    Thanks for leading me towards the listener approach!

    0 讨论(0)
  • 2021-02-01 10:13

    i have created a simple svg animations library based on a project by another person, for now, only Paths can be animated but more shapes and animations will be added in the future

    https://www.npmjs.com/package/react-native-svg-animations

    0 讨论(0)
提交回复
热议问题