React Native:如何为图像旋转设置动画? [英] React Native: How do you animate the rotation of an Image?

查看:1259
本文介绍了React Native:如何为图像旋转设置动画?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

旋转是一种样式转换,在RN中,您可以旋转这样的东西

Rotation is a style transform and in RN, you can rotate things like this

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

但是,要为RN中的内容添加动画效果,您必须使用数字而不是字符串。您是否仍可以在RN中为转换设置动画,或者我必须拿出某种精灵表并以fps更改Image src?

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?

推荐答案

您实际上可以使用 interpolate 方法对字符串进行动画处理。 interpolate 取一个值范围,通常0到1在大多数情况下效果很好,然后将它们插值到一个值范围内(这些值可能是字符串,数字,甚至返回的函数一个值)。

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).

您要做的是获取一个现有的Animated值,并将其通过插值函数传递,如下所示:

What you would do is take an existing Animated value and pass it through the interpolate function like this:

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'}} />

如果要循环循环,请添加 Animated.loop

In case if you want to do the rotation in loop, then add the Animated.timing in the Animated.loop

Animated.loop(
 Animated.timing(
   this.spinValue,
   {
    toValue: 1,
    duration: 3000,
    easing: Easing.linear
    useNativeDriver: true
   }
 )
).start();

这篇关于React Native:如何为图像旋转设置动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆