다시 활성화시키자

王林
풀어 주다: 2024-08-29 11:08:04
원래의
261명이 탐색했습니다.

텍스트와 이미지를 그리는 것도 중요하지만 UI 프레임워크의 실제 테스트는 애니메이션 콘텐츠가 얼마나 좋은지 여부입니다.

Let

그리고 제가 테스트한 애니메이션은 Apple의 샘플 코드를 기반으로 한 클래식 MoveMe입니다.

화면에 상자 세 개를 그리는 아이디어입니다. 선택하면 상자의 색상이 변경되고 크기가 확대된 다음 드래그 동작으로 이동할 수 있으며 최종적으로 놓으면 원래 색상과 크기로 다시 복원됩니다.

React Native의 Reanimated 라이브러리를 사용하여 해당 샘플을 빌드해 보겠습니다.

설정

공식 문서를 따르고 있지만 해당 템플릿을 사용하고 있지 않습니다. 그래서 빈 템플릿으로 기본 프로젝트를 만들고 종속성을 설치했습니다

npx create-expo-app playground --template blank
npx expo install react-native-reanimated
npx expo install react-native-gesture-handler

로그인 후 복사

다음으로 플러그인을 추가했습니다

module.exports = function (api) {
  api.cache(true);
  return {
    presets: ["babel-preset-expo"],
    plugins: ["react-native-reanimated/plugin"],
  };
};

로그인 후 복사

그런 다음 화면에 사각형 3개를 그립니다.

import { StatusBar } from "expo-status-bar";
import { StyleSheet, View } from "react-native";
import Animated from "react-native-reanimated";

function Square() {
  return <Animated.View style={styles.square}></Animated.View>;
}

export default function App() {
  return (
    <View style={styles.container}>
      <StatusBar style="auto" />
      <Square />
      <Square />
      <Square />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "space-evenly",
  },
  square: {
    width: 100,
    height: 100,
    backgroundColor: "blue",
  },
});

로그인 후 복사

Let

제스처 핸들러 추가

제스처 핸들러에 대한 지원을 추가하려면 먼저 GestureHandlerRootView 내에 콘텐츠를 래핑해야 합니다

<GestureHandlerRootView style={styles.container}>
  <Square />
  <Square />
  <Square />
</GestureHandlerRootView>

로그인 후 복사

그런 다음 각 사각형을 GestureDetector로 래핑합니다

function Square() {
  const gesture = Gesture.Pan();

  return (
    <GestureDetector gesture={gesture}>
      <Animated.View style={styles.square} />
    </GestureDetector>
  );
}

로그인 후 복사

동작 이벤트 처리

제스처를 처리하려면 먼저 State와 비슷하지만 애니메이션 상태를 위한 SharedValue를 생성해야 합니다. 예를 들어 선택 시 배경색을 변경하려면 onBegin 및 onFinalize 이벤트를 수신하고 스타일을 업데이트해야 합니다.

function Square() {
  const isPressed = useSharedValue(false);
  const animStyle = useAnimatedStyle(() => {
    return {
      backgroundColor: isPressed.value ? "red" : "blue",
    };
  });

  const gesture = Gesture.Pan()
    .onBegin(() => {
      isPressed.value = true;
    })
    .onFinalize(() => {
      isPressed.value = false;
    });

  return (
    <GestureDetector gesture={gesture}>
      <Animated.View style={[styles.square, animStyle]} />
    </GestureDetector>
  );
}

로그인 후 복사

드랙을 지원하는 것도 비슷합니다. 시작 위치와 현재 위치를 저장한 다음 onChange 이벤트에서 현재 위치를 업데이트해야 합니다. onChange는 최종 현재 위치를 계산하기 위해 시작 위치에 추가해야 하는 델타 변경 사항을 제공합니다. 그런 다음 마지막으로 onFinalize 이벤트에서 시작 위치와 현재 위치를 동기화할 수 있습니다.

function Square() {
  const isPressed = useSharedValue(false);
  const startPos = useSharedValue({ x: 0, y: 0 });
  const pos = useSharedValue({ x: 0, y: 0 });
  const animStyle = useAnimatedStyle(() => {
    return {
      backgroundColor: isPressed.value ? "red" : "blue",
      transform: [
        { translateX: pos.value.x },
        { translateY: pos.value.y },
        { scale: withSpring(isPressed.value ? 1.2 : 1) },
      ],
    };
  });

  const gesture = Gesture.Pan()
    .onBegin(() => {
      isPressed.value = true;
    })
    .onChange((e) => {
      pos.value = {
        x: startPos.value.x + e.translationX,
        y: startPos.value.y + e.translationY,
      };
    })
    .onFinalize(() => {
      isPressed.value = false;
      startPos.value = {
        x: pos.value.x,
        y: pos.value.y,
      };
    });

  return (
    <GestureDetector gesture={gesture}>
      <Animated.View style={[styles.square, animStyle]} />
    </GestureDetector>
  );
}

로그인 후 복사

여기 있습니다

Let

참고자료

  • 반응 네이티브 재활성화
  • 반응 네이티브 제스처 처리기
  • React Native Reanimated 2를 사용한 PanGestureHandler의 기본
  • UIKit을 사용한 데이터 기반 UI

위 내용은 다시 활성화시키자의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!