【问题标题】:How to animate a part of an svg file in React Native如何在 React Native 中为 svg 文件的一部分设置动画
【发布时间】:2023-03-16 20:21:01
【问题描述】:

我正在开发一个 react 本机应用程序,我需要对 svg 文件的一部分进行动画处理(围绕中心点旋转)。如何访问我想要制作动画的组件?

我尝试将 svg 文件转换为 jsx 格式。但我仍然无法访问要旋转的组件

App.js:

import React from 'react';
import { StyleSheet, Text, View, Animated } from 'react-native';
import SvgComponent from './assets/hotFan';


class App extends React.Component {
  constructor(props){
    super(props);
    this.animation = new Animated.Value(0);
  }

  render(){
    const rotation = this.animation.interpolate({
      inputRange: [0, 1],
      outputRange: ['0deg', '360deg']
    });

    return (
      <Animated.View style={{transform: [{rotate: rotation}]}}>
          <SvgComponent/>
      </Animated.View>
    );
  }

  componentDidMount() {

    Animated.loop(
      Animated.timing(this.animation, {toValue: 1, duration: 2000})
    ).start();    
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default App;

我无法将整个组件代码放在这里,因为它超过了字符数限制。但您可以使用https://www.smooth-code.com/open-source/svgr/playground/https://drive.google.com/file/d/1lKaSWTO1_0cQQN6rtdaw_yWE9qa5nSjV/view?usp=sharing 转换为jsx 文件

实际代码会旋转整个组件,但内部箭头是应该旋转的,而不是整个组件。

【问题讨论】:

    标签: javascript react-native animation svg react-native-svg


    【解决方案1】:

    您可以将 SVG 拆分为两个组件:箭头组件,它是 SVG 的静态部分和Fan 组件 - 动画部分。然后用Animated.View 包裹Fan 组件并传递给你动画:

     <View>
         <SVG />
         <Animated.View style={animatedStyle}>
            <Fan />
         </Animated.View>
     </View>
    

    动画组件将被“绝对”定位在包装中,并将渲染动画属性:

    const interpolateRotation = this.animatedValue.interpolate({
        inputRange: [0, 1],
        outputRange: ['360deg', '0deg'], 
    });
    
    const animatedStyle = {
        position: 'absolute',
        top: 0,
        left: 0,
        transform: [
            { rotate: interpolateRotation }
        ]
    }
    

    最后,最简单的部分是准备动画并启动它:

    animatedValue = new Animated.Value(1);
    
    componentDidMount() {
        this.startAnimation();
    }
    
    startAnimation = () => {
        this.animatedValue.setValue(0);
        Animated.timing(this.animatedValue, {
          toValue: 1,
          duration: 1500,
          easing: Easing.linear,
        }).start(() => this.startAnimation())
    }
    

    我创建了一个工作演示 here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-19
      • 2017-10-08
      • 2018-05-07
      • 2015-09-11
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 2021-06-09
      相关资源
      最近更新 更多