0

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

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

应用程序.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 文件

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

4

1 回答 1

1

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

 <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())
}

我在这里创建了一个工作演示。

于 2019-09-25T09:45:22.750 回答