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

标签 svg react-native

ReactNative:

<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 使圆缩放。我已经尝试过这个:

    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给出了谨慎使用它的建议,因为它可能会对 future 的性能产生影响。

那么最好的方法是什么?

最佳答案

使用 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 毫秒)超时触发时动画的样子。

circle animation with setnativeprops

因此,您需要更改的主要内容是在监听器中使用 setNativeProps 而不是使用 setState。这会进行 native 调用并绕过重新计算整个组件,在我的例子中,这非常复杂且缓慢。

感谢您引导我走向倾听者的道路!

关于svg - 如何在react-native中使用Animated制作svg动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39094349/

相关文章:

css - SVG 动画步进旋转

javascript - 在 paper.js 中对导入的 svg 的路径段进行动画处理

javascript - 我可以在 React Native 上向 this.props.children 添加额外的回调吗?

ios - 在 Docker 中使用 FaSTLane 构建 iOS 应用

google-chrome - Chrome 中放大后,svg 图案内的图像变得模糊

javascript - 鼠标悬停时 SVG 比例 - 元素消失

jquery - 动画后如何在 SVG 中保持原始破折号?

reactjs - 如何在使用 Expo 的同时在 IOS 和 Android 上使用谷歌地图

android - com.google.android.gms :play-services-base compile and runtime collision in react native

android - 在 React Native 项目中为 Android 添加服务