animation 사용

이제 우리는 RN에서 animation을 사용하는 법에 대해 알아 보겠습니다.

React Native에서는 animation을 약간 특이한 방법(?)으로 지원을 합니다. UI적인 animation을 지원하지 않고 단순히 값만을 animation 할 수 있게 해줍니다. 제가 설명을 이상하게 해서 이해가 안될텐데 예를 들어서 설명을 해보겠습니다.

먄약 어떤 image의 위치가 (100,100)이라고 해봅시다. 우리가 하고 싶은 animation은 이 image가 위치(200,200)으로 움직이게 하고 싶다고 가정하면 animation이라는건 (100,100) -> (200,200)으로 위치가 연속적으로 변하는 것을 의미합니다. 만약 animation이 필요없다면 this.state.x, this.state.y를 처음에 100으로 두고, 그뒤 200으로 바꾸면 됩니다. animation을 하고 싶다면 이 x,y의 값이 연속적으로 100에서 200으로 바뀐다면 animation이 되겠지요.

react는 이렇게 값이 연속적으로 바뀌는 걸 지원합니다. 설명이 이상하군요. 실제로 코드를 볼까요? position absoulte에서 사용한 코드를 이용해보죠.

class gitbookTestUI extends Component {
  constructor(props) {
    super(props);
    this.state = {
      x: new Animated.Value(100),
    };
  }
  click(){
    Animated.spring(
      this.state.x,
      {toValue: 200}
    ).start();
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={{backgroundColor: '#FFAAAA', flex: 1}}>
          <View style={{position: 'absolute', backgroundColor: '#FFFFFF', right: 30, bottom: 30, height: 30, width: 30}}></View>
        </View>
        <View style={{flexDirection: 'row', flex: 1}}>
          <View style={{backgroundColor: '#FFAA00', flex: 1}}>
            <View style={{position: 'absolute', backgroundColor: '#FFFFFF', right: 30, bottom: 30, height: 30, width: 30}}></View>
          </View>
          <View style={{backgroundColor: '#00AAAA', flex: 1}}></View>
        </View>
        <View style={{backgroundColor: '#FF00AA', flex: 1}}>
          <View style={{position: 'absolute', backgroundColor: '#FFFFFF', right: 30, bottom: 30, height: 30, width: 30}}></View>
        </View>
        <TouchableOpacity onPress={this.click.bind(this)}>
          <Animated.View style={{position: 'absolute', backgroundColor: '#AAAAAA', right: this.state.x, bottom: 40, height: 30, width: 30}}></Animated.View>
        </TouchableOpacity>
      </View>
    );
  }
}

이걸 실행한뒤에 회색박스를 눌러보세요. 움직이는게 보이죠.

좀더 여기서 발전시켜보죠.

click(){
    if(this.state.x._value == 100){
      Animated.spring(
        this.state.x,
        {toValue: 200}
      ).start();
    }
    else{
      Animated.timing(
        this.state.x,
        {toValue: 100}
      ).start();
    }

  }

click함수를 이렇게 바꾸고 실행하면 어떻게 될까요? 누르면 왓다갓다 하게 됩니다. 근데 갈때는 올때 animation이 다릅니다. 속도가 다르죠. 그 이유는 바로 spring과 timing때문입니다. react-native docs animated 을 보시면 아시겠지만 여러가지 animation을 지원합니다(결국엔 어떤속도로 값이 바뀌느냐 를 지원하는거지만요, 여기있는 api들을 통해서 우리는 많은 animation을 만들수 있습니다.) docs을 읽어보고 잘 모르는 것을 한개한개 실제로 실행해서 연습을 해보시면 아마 금방 어떤 느낌인지 아실거라고 생각됩니다.

results matching ""

    No results matching ""