如何在react-native中使用Animated制作svg动画

问题描述 投票:10回答:3

反应原生:

<ScrollView style={styles.container}>
    <Svg
      height="100"
      width="100">
        <Circle
          cx="50"
          cy="50"
          r="50"
          stroke="blue"
          strokeWidth="2.5"
          fill="green"/>
      </Svg>
</ScrollView>

我想用Animated.Value制作Circle比例。我试过这个:

    let AnimatedScrollView = Animated.createAnimatedComponent(ScrollView);
    let AnimatedCircle = Animated.createAnimatedComponent(Circle);

    <ScrollView style={styles.container}>
            <Svg
              height="100"
              width="100">
                <AnimatedCircle
                  cx="50"
                  cy="50"
                  r={this.state.animator}
                  stroke="blue"
                  strokeWidth="2.5"
                  fill="green"/>
              </Svg>
        </ScrollView>

然后闪回,没有错误。

我能怎么做?


更新2016.8.24

我发现了一种新方法而不是requestAnimationFrame:

构造函数:

this.state = {
      animator: new Animated.Value(0),
      radius: 1,
    };

    this.state.animator.addListener((p) => {
      this.setState({
        radius: p.value,
      });
    });

渲染:

<Circle
    cx="50"
    cy="50"
    r={this.state.radius}
    stroke="blue"
    strokeWidth="2.5"
    fill="green"/>

但是,the guides在这里谨慎地使用它,因为它可能会在未来对性能产生影响。

那么最好的方法是什么?

svg react-native
3个回答
12
投票

使用setNativeProps可以获得更好的性能。

我做了一些修修补补,发现了一种更有效的方法,可以使用addListenersetNativeProps

构造函数

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() {
  return(
    <Svg height="400" width="400">
      <AnimatedCircle ref={ ref => this._myCircle = ref } cx="250" cy="250" r="50" fill="black" />
    </Svg>
  )
}

结果

这就是当2秒(2000毫秒)超时触发时动画的样子。

所以,你需要改变的主要是使用setNativeProps而不是在你的监听器中使用setState。这使得本机调用和绕过重新计算整个组件,在我的情况下,这是非常复杂和缓慢的。

感谢您引导我走向听众的方法!


1
投票

我已经基于另一个人的项目创建了一个简单的svg动画库,现在,只有Paths可以动画,但将来会添加更多的形状和动画

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


0
投票

没有更好的答案,我通过添加监听器到Animated.Value变量实现,你可以从我的问题描述中获得更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.