首页 > 解决方案 > React Native 动画图像旋转播放和暂停

问题描述

如何使图像停止旋转并从该位置开始旋转成为可能。谢谢你。

import React, {Component} from 'react';

import {StyleSheet, View, Animated, Image, Easing} from 'react-native';

export default class App extends Component<{}> {

  constructor() {

    super()

    this.RotateValueHolder = new Animated.Value(0);

  }

  componentDidMount() {

    this.StartImageRotateFunction();

  }

  StartImageRotateFunction() {

    this.RotateValueHolder.setValue(0)

    Animated.timing(
        this.RotateValueHolder,
        {
            toValue: 1,
            duration: 3000,
            easing: Easing.linear
        }
    ).start(() => this.StartImageRotateFunction())

  }

  render() {

    const RotateData = this.RotateValueHolder.interpolate({
        inputRange: [0, 1],
        outputRange: ['0deg', '360deg']
    })

    return (
        <View style={styles.container}>

            <Animated.Image
                style={{
                    width: 250,
                    height: 230,
                    transform: [{rotate: RotateData}]
                }}
                source={{uri: 'https://reactnativecode.com/wp-content/uploads/2017/10/Butterfly.png'}}/>

        </View>
      );
   }  
}



const styles = StyleSheet.create({

  container: {

    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  }
});

标签: reactjsreact-native

解决方案


最简单的方法是调用RotateData.stopAnimation()

小吃示例:https ://snack.expo.io/B1mPsdt_Q

相关代码:

  componentDidMount() {
    Animated.timing(
      this.rotate,
      { toValue: 1, duration: 3000 }
    ).start()

    this.timeout = setTimeout(() => {
      this.rotate.stopAnimation(e => {
        console.log('animation stopped', e)
      })
    }, 2000)

    this.timeout = setTimeout(() => {
      Animated.timing(
        this.rotate,
        { toValue: 1, duration: 2000}
      ).start()
    }, 4000)
  }

如您所见,我已将旋转设置为运行 10 秒,并在 2 秒后超时停止。如果您打开零食,您会看到该物品根据需要停止旋转。4 秒后,动画将在调用时从当前位置恢复,无需任何添加配置。

同样重要的是要注意动画在当前值上停止,并stopAnimation()接受回调作为参数,并且该回调将在动画停止时传递动画的值。


推荐阅读