Animated Function

민갱·2023년 1월 19일

RN

목록 보기
2/2

Component

  • Ewns : 카드 방향과 맞는 버튼으로 움직이는 게임(동서남북이면 동서남북이지,,,동서북남 뭐냐…ㅎㅎ)
  • CardAni : 카드의 폰트 이름을 마추기 게임 (API 받아서 체크하는 내용은 어느것이든 적용 가능하지 않을까..)
  • AnimatedDrag : 드래그 앤 드롭 에니메이션
  • AnimatedMove : 상하 + 회전 에니메이션
  • Animated_ValueXY : 상하좌우 이동 에니메이션

Built with

  • React Native
  • TypeScript
  • styled-component

공식문서.

PanResponder

  • PanResponder는 여러 터치를 단일 제스처로 조정한다.
  • 추가 터치에 대한 단일 터치 제스처를 복원하고 기본 멀티 터치 제스처를 인식하는 데 사용할 수 있다.
  • 기본적으로 PanResponder는 활성 제스처를 방해하는 장기 실행 js 이벤트를 차단하는 InteractionManager 을 보유한다.
  1. PanResponder 생성 및 컴포넌트와의 결합

    1. PanResponder 생성
    2. 컴포넌트와의 결합
  2. gestureState

    ex. onPanResponderMove: (_, {dx, dy}) => {}
    1. stateID: 제스처 상태의 ID (화면에 하나 이상의 터치가 있는 한 지속됨)
    2. moveX, moveY: 최근 이동한 터치의 최신 화면 좌표 (View의 중심이 아니라 터치한 좌표)
    3. x0, y0: 응답자 부여의 화면 좌표
    4. dx, dy: 터치가 시작된 이후 제스처의 누적거리
    5. vx, by: 제스처의 현재 속도
    6. numberActiveTouches: 현재 화면의 터치 수
  3. Styled-component 로 Animated 컴포넌트 생성 방법

const Card = styled.View`
  background-color: white;
  width: 300px;
  height: 300px;
  justify-content: center;
  align-items: center;
  border-radius: 12px;
  box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.2);
`;

const AnimatedCard = Animated.createAnimatedComponent(Card);

// 두가지 방법이지만 아래 방법이 더 많이 사용됨

const CardAnimated = styled(Animated.createAnimatedComponent(View))`
  background-color: white;
  width: 300px;
  height: 300px;
  justify-content: center;
  align-items: center;
  border-radius: 12px;
  box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.2);
  position: absolute;
`;
  1. useRef로 Animated 연결

const scale = useRef(new Animated.Value(1)).current;
const position = useRef(new Animated.Value(0)).current;
중요 ** const panResponder = useRef(PanResponder.create({...}).current
  1. interpolate

    • extrapolate: 'clamp', : 범위 밖으로 나갔을 경우 실행 옵션
      • input 범위 바깥으로 나갔을 때 어떻게 처리할 지 명시 할수 있다.
      • extend : 끝이 한계치를 넘어서 계속 진행하는것
      • identity :
      • clamp : 더이상 움직이지 않게 하는것
    const rotation = position.interpolate({
        inputRange: [-250, 250],
        outputRange: ['-15deg', '15deg'],
        // extrapolate: 'clamp',
    	    // input 범위 바깥으로 나갔을 때 어떻게 처리할 지 명시 할수 있다.
    	    // extend : 끝이 한계치를 넘어서 계속 진행하는것
    	    // identity :
    	    // clamp : 더이상 움직이지 않게 하는것
      });
    
  2. spring, timing

    const goCenter = Animated.spring(position, {
        toValue: 0,
        useNativeDriver: true,
      });
    const onDropScale = Animated.timing(scale, {
        toValue: 0,
        useNativeDriver: true,
        duration: 50,
        easing: Easing.linear,
      });
  3. PanResponder.create({})

    • onStartShouldSetPanResponder
      // 손가락 이벤트를 감지할 것인가 말 것인가를 정하는 것
            onStartShouldSetPanResponder: () => true,
    • onPanResponderGrant
      // panResponder가 움직이기 시작하면 이 함수 실행 시킨다.
            onPanResponderGrant: () => {
              onPressIn.start();
            },
    • onPanResponderMove
      // panResponder가 움직이기 시작하면 이 함수 실행 시킨다.
            onPanResponderMove: (_, {dx, dy}) => {
              
              setTimeout(() => {
                Animated.timing(position, {
                  toValue: 0,
                  duration: 50,
                  useNativeDriver: true,
                }).stop(() => {
                  position.setValue(0);
                  nextIcon();
                });
              }, 1000);
              position.setValue({x: dx, y: dy});
            },
      
    • onPanResponderRelease
      • Animated.sequence([]) : 배열 안의 함수를 순차적으로 실행시킨다.

      • Animated.parallel([]) : 배열 안의 함수를 동시에 실행시킨다.

      • Animated.timing - 시간의 경과에 따라 값을 애니메이션

      • Animated.spring - 스프링(spring) 물리 모델을 사용하여 애니메이션(animate)

      • Animated.decay (쇠퇴) - 초기 속도에서 시작하여 점차 값을 늦추기
        - useNativeDriver: true : useNativeDriver:true 옵션을 사용하여 애니메이션을 네이티브 UI로 움직이는 방법이 있습니다.
        - js UI를 사용하지 않고 네이티브 UI를 사용해서 더욱 부드럽고 빠르게 움직인다.
        - toValue : 목표 값
        - duration : 이동 속도
        - easing : type - timing에서만 사용되는 옵션 (번역하면 뭐 물리적 이동 옵션 어쩌구 저쩌구인데,, 직선으로 빠르게 움직인다고 보면 될거같음…ㅎㅎ)
        The Easing module implements common easing functions. This module is used by [Animated.timing()](https://reactnative.dev/docs/animated#timing) to convey physically believable motion in animations.

        // panResponder가 움직임이 끝낫을떄! 즉 터치가 끝났을때!
              onPanResponderRelease: (_, {dx, dy}) => {
                  Animated.sequence([
                    Animated.parallel([onDropOpacity, onDropScale, onChkOpacity2]),
                    Animated.timing(position, {
                      toValue: 0,
                      duration: 50,
                      easing: Easing.linear, // 직선으로 빠르게 움직임
                      useNativeDriver: true,
                    }),
                  ]).start(() => {
                    nextIcon(0);
                  });
        			},
    • getTranslateTransform : [{translateX: }, {translateY :}] 와 동일하게 한번에 배열로 받아주는 함수
      position.getTranslateTransform();
    • Components
      <IconCard
                  // 위에서 선언한 panResponder(PanResponder.create를 한 변수)
      						//의 panHandlers를 반드시 연결해줘야함
                  {...panResponder.panHandlers}
                  style={{
                    opacity: opacity,
                    transform: [
                      ...position.getTranslateTransform(),
                      {
                        scale,
                      },
                    ],
                  }}>

profile
가보자고

0개의 댓글