Javascript React Native:如何设置图像旋转的动画?

Javascript React Native:如何设置图像旋转的动画?,javascript,react-native,animation,rotation,transform,Javascript,React Native,Animation,Rotation,Transform,旋转是一种样式转换,在RN中,可以像这样旋转 render() { return ( <View style={{transform:[{rotate: '10 deg'}]}}> <Image source={require('./logo.png')} /> </View> ); } render(){ 返回( ); } 但是,要在RN中设置动画,必须使用数字,而不是字符串。你仍然可以在R

旋转是一种样式转换,在RN中,可以像这样旋转

  render() {
    return (
      <View style={{transform:[{rotate: '10 deg'}]}}>
        <Image source={require('./logo.png')} />
      </View>
    );
  }
render(){
返回(
);
}

但是,要在RN中设置动画,必须使用数字,而不是字符串。你仍然可以在RN中设置变换的动画,还是我必须拿出某种精灵表并在某些fps处更改图像src?

你实际上可以使用
插值
方法设置字符串的动画<代码>插值获取一个值范围,通常0到1适用于大多数情况,并将其插值为一个值范围(可以是字符串、数字,甚至是返回值的函数)

您要做的是获取现有动画值,并将其通过插值函数,如下所示:

spinValue = new Animated.Value(0);

// First set up animation 
Animated.timing(
    this.spinValue,
  {
    toValue: 1,
    duration: 3000,
    easing: Easing.linear, // Easing is an additional import from react-native
    useNativeDriver: true  // To make use of native driver for performance
  }
).start()

// Next, interpolate beginning and end values (in this case 0 and 1)
const spin = this.spinValue.interpolate({
  inputRange: [0, 1],
  outputRange: ['0deg', '360deg']
})
<Animated.Image
  style={{transform: [{rotate: spin}] }}
  source={{uri: 'somesource.png'}} />
然后在组件中使用它,如下所示:

spinValue = new Animated.Value(0);

// First set up animation 
Animated.timing(
    this.spinValue,
  {
    toValue: 1,
    duration: 3000,
    easing: Easing.linear, // Easing is an additional import from react-native
    useNativeDriver: true  // To make use of native driver for performance
  }
).start()

// Next, interpolate beginning and end values (in this case 0 and 1)
const spin = this.spinValue.interpolate({
  inputRange: [0, 1],
  outputRange: ['0deg', '360deg']
})
<Animated.Image
  style={{transform: [{rotate: spin}] }}
  source={{uri: 'somesource.png'}} />

不要忘记添加属性useNativeDriver,以确保您从该动画中获得最佳性能:

// First set up animation 
Animated.timing(
    this.state.spinValue,
  {
    toValue: 1,
    duration: 3000,
    easing: Easing.linear,
    useNativeDriver: true
  }
).start();

给像我这样的新手一个提示: 为了制作其他东西的动画,您需要将其包装起来,这样才能工作。否则编译器将在该转换属性上死机:

import {Animated} from 'react-native';
...
//animation code above
...
<Animated.View style={{transform: [{rotate: spin}] }} >
   <YourComponent />
</Animated.View>
从'react native'导入{Animated};
...
//上面的动画代码
...

但是对于一个图像(动画.image),上面的例子是100%正确的。

Nice!简明扼要!另外,在rnplay示例中,您如何知道start()可以接受回调?在Facebook的注册护士网站上找不到相关的文档。啊,是的。我想我记得看到布朗尼菲德(杰森·布朗)发了一些关于它的帖子。它确实需要回调,但在动画完成时会触发回调。退房,然后。他用动画做了很多例子。我很高兴这有帮助:)记住
this.state={spinValue:new Animated.Value(0)}
为此创建了一个示例要点:使用
loop
使其无限循环
Animated.loop(Animated.timeing(this.spinValue,{toValue:1,持续时间:1000,easing:easing.linear,useNativeDriver:true,})).start()