javascript - 如何在 React Native 中为 svg 文件的一部分设置动画
问题描述
我正在开发一个反应本机应用程序,我需要对 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 文件
实际代码旋转整个组件,但内部箭头是应该旋转的,而不是整个组件。
解决方案
您可以将 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())
}
我在这里创建了一个工作演示。
推荐阅读
- r - R - 是否可以填写保存为对象的函数参数?
- python - 使用 Beautiful Soup 从 Google 中提取每小时的天气数据
- ios - 改变 TabView 的动画(pageTabViewStyle)
- module - 是否可以与多个应用程序共享 nrwl nx monorepo 中的用户模块(注册、登录等)
- ios - Swift Alamofire RequestInterceptor - 如何返回从服务器收到的原始错误?
- javascript - 使用交叉点观察器制作动画
- android - AppCenter Xamarin Android 在新版本发布时通知外部测试人员
- android-studio - 在为 Espresso 测试创建活动之前更改共享偏好
- ios - 反应原生 forceRTL false 在 iOS 上不起作用
- nestjs - 使用 NVM 设置 NestJS 项目时出现 EBADENGINE 警告