Javascript React Native:如何为图像的旋转设置动画?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37445090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React Native: How do you animate the rotation of an Image?
提问by sdfsdf
Rotation is a style transform and in RN, you can rotate things like this
旋转是一种样式变换,在 RN 中,您可以像这样旋转
render() {
return (
<View style={{transform:[{rotate: '10 deg'}]}}>
<Image source={require('./logo.png')} />
</View>
);
}
However, to animate things in RN, you have to use numbers, not strings. Can you still animate transforms in RN or do I have to come up with some kind of sprite sheet and change the Image src at some fps?
但是,要在 RN 中制作动画,您必须使用数字,而不是字符串。您是否仍然可以在 RN 中为转换设置动画,或者我是否必须提出某种精灵表并以某些 fps 更改图像 src?
回答by Nader Dabit
You can actually animate strings using the interpolate
method. interpolate
takes a range of values, typically 0 to 1 works well for most things, and interpolates them into a range of values (these could be strings, numbers, even functions that return a value).
您实际上可以使用该interpolate
方法为字符串设置动画。interpolate
取一系列值,通常 0 到 1 适用于大多数情况,并将它们插入到一系列值中(这些值可以是字符串、数字,甚至是返回值的函数)。
What you would do is take an existing Animated value and pass it through the interpolate function like this:
您要做的是采用现有的 Animated 值并将其传递给 interpolate 函数,如下所示:
spinValue = new Animated.Value(0)
// First set up animation
Animated.timing(
this.spinValue,
{
toValue: 1,
duration: 3000,
easing: Easing.linear
useNativeDriver: true // To make use of native driver for performance
}
).start()
// Second interpolate beginning and end values (in this case 0 and 1)
const spin = this.spinValue.interpolate({
inputRange: [0, 1],
outputRange: ['0deg', '360deg']
})
Then use it in your component like this:
然后像这样在你的组件中使用它:
<Animated.Image
style={{transform: [{rotate: spin}] }}
source={{uri: 'somesource.png'}} />
In case if you want to do the rotation in loop, then add the Animated.timing
in the Animated.loop
如果您想在循环中进行旋转,请Animated.timing
在Animated.loop
Animated.loop(
Animated.timing(
this.spinValue,
{
toValue: 1,
duration: 3000,
easing: Easing.linear
useNativeDriver: true
}
)
).start();
回答by jeevium
Don't forget to add property useNativeDriverto ensure that you get the best performance out of this animation:
不要忘记添加属性useNativeDriver以确保您从该动画中获得最佳性能:
// First set up animation
Animated.timing(
this.state.spinValue,
{
toValue: 1,
duration: 3000,
easing: Easing.linear,
useNativeDriver: true
}
).start();