React Native Lottie View 动画播放/暂停问题

Her*_*vic 6 animation react-native lottie

我正在使用 React Native Lottie Wrapper 在屏幕上显示动画。
我需要一个播放/暂停/恢复动画的功能。

这是我的代码的一部分:

...

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

static navigationOptions = {
  title: "Details",
  headerStyle: {
    backgroundColor: '#f4511e',
  },
  headerTintColor: '#fff',
  headerTitleStyle: {
    fontWeight: 'bold',
  },
  headerTruncatedBackTitle: 'List'
};

componentDidMount() {
  this.animation.play();
}

playLottie() {
 console.log('play');
}

pauseLottie() {
  console.log('pause');
}

render() {
  return (
    <View>
      <Animation
        ref={animation => { this.animation = animation; }}
        source={require('../../../../assets/anim/balloons.json')}
        style={{height: 300, width: '100%'}}
        loop={false}
        progress={this.state.progress}
      />
      <Text>Course with id: {this.props.navigation.state.params.courseId}</Text>
        <Button 
          onPress={this.playLottie}
          title="Play Lottie"
          color="#841584"
          accessibilityLabel="Play video"
        />
        <Button 
          onPress={this.pauseLottie}
          title="Pause Lottie"
          color="#841584"
          accessibilityLabel="Pause video"
        />
     </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

...
Run Code Online (Sandbox Code Playgroud)

动画播放得很好,但我无法暂停和恢复。
有人有解决这个问题的办法吗?

PS我尝试在pauseLottie()方法中使用this.animation,但它说这是未定义的。

先感谢您!

小智 8

您可以通过更改 prop 来暂停和播放 Lottie 动画speed,其中speed={0}将 LottieView 组件置于暂停状态并speed={1}以正常速度播放。

这是一个例子:

playAnimation = () => {
    this.setState({speed: 1})
}

pauseAnimation = () => {
    this.setState({speed: 0})
}

<LottieView
    source={this.state.sourceAnimation}
    speed={this.state.speed} />
Run Code Online (Sandbox Code Playgroud)


Her*_*vic 1

对我来说它效果不佳:我们必须添加 setValue(0),然后我们需要改进暂停/重新启动以保持播放速度并更改缓动功能以避免缓慢重新启动。我们还添加循环:

constructor(props) {
  super(props);
  this.playLottie.bind(this);
  this.pauseLottie.bind(this);
  this.state = {
    progress: new Animated.Value(0),
    pausedProgress: 0
  };
}

playLottie = () => {
  Animated.timing(this.state.progress, {
    toValue: 1,
    duration: (10000 * (1 - this.state.pausedProgress)),
    easing: Easing.linear,
  }).start((value) => { 
    if (value.finished) this.restartAnimation();
  });
}

restartAnimation = () => {
  this.state.progress.setValue(0);
  this.setState({ pausedProgress: 0 });
  this.playAnimation();
}

pauseLottie = () => {
  this.state.progress.stopAnimation(this.realProgress);
}

realProgress = (value) => {
  console.log(value);
  this.setState({ pausedProgress: value });
};
...
Run Code Online (Sandbox Code Playgroud)

(现在)对我来说,一切正常!播放和暂停选项按预期工作。