React Native loading旋转动画的实现

在决定做一次loading动画的时候,我首先看了一下官方文档:React Native Animated的使用。不过官方文档看得云里雾里,必须通过自己动手才能真正了解怎么做。

首先需要在自定义view(当然也可以不自定义,不过建议最好这种view可以自己定义防止state与其他view冲突)。在自定义view的constructor方法中,需要对动画初始值进行设置:

constructor(props) {
    super(props);
    this.state = {
        rotateValue: new Animated.Value(0),
    };
}

接着需要实现动画的逻辑rotateValue其实是作为一个会变动的值,通过值的变动来更新view的显示效果的。第二步在componentDidMount方法中执行动画:

componentDidMount() {
    this.state.rotateValue.setValue(0);
    Animated.timing(this.state.rotateValue,{
        toValue: 360*TIMES,
        duration: 800*TIMES,
        easing: Easing.linear
        }).start();// 开始spring动画
}

timing方法的说明是,从时间的范围来改变渐变的值,其中第一个参数就是需要变化的值,toValue就是要变动到的值,在这里设置的比较大,就是让他一直旋转。durationg是持续时间。easing是渐变函数,类似于android中的插值器,linear就是线性变化LinearInterpolator。

最后就是render view了,先看下代码:

render() {
    return (
        <View style={styles.paginationView}>
             <Animated.Image
             style = {[styles.bottom_loading_style,
                    {transform:[{rotate: this.state.rotateValue
                      .interpolate({inputRange: [0, 360],outputRange: ['0deg', '360deg']})
                      }]
                    }]}
             source = {THUMB_URLS[0]}
             resizeMode = "contain"/>
             <Image style = {styles.title_btn_style} 
                source = {THUMB_URLS[1]}  resizeMode = "contain"/>
        </View>
    );
}

重点在第一个Image的style设置,因为RN规定了一些View可以直接使用Animated,其中有View,Text,Image,所以在需要使用Animated的地方需要使用Animated.Image。动画的设置也是以style的方式加进去的,此处需要设置多个style所以用到了大括号,当然也可以直接写进style中。

后面的transform用来设置组合动画,我这里使用了一个,然后通过插值器的方法将值转换到角度的变化。最开始的时候我并没有使用插值器,而是直接用rotate: 0 ,来进行设置,但是却提示在使用rotate这个动画的时候不能使用int而应该用string,而这时候如果更换成 rotate: ‘0deg’,则会提示

error while updating property transform of a view managed by RCTImageVIew

这个确实很奇怪,在stackoverflow上查了很久发现很多人说是RN版本问题,最后通过插值器的方法将int转换成他需要的deg才算圆满结束。