首页 > 解决方案 > React Native Reanimated 2 为 SVG 路径的长度设置动画

问题描述

我正在尝试将 SVG 路径的长度从 0 动画到 React Native Reanimated 2 中的全长。这是我的示例路径:

const AnimatedPath = Animated.createAnimatedComponent(Path);

const animatedProps = useAnimatedProps(() => {
  const path =
    `M${width * 0.182} ${height * 0.59} ` +
    `L${width * 0.443} ${height * 0.59} ` +
    `L${width * 0.443} ${height * 0.39} `;
  return {
    d: path,
  };
});

return (
  <Svg height="100%" width="100%">
    <AnimatedPath animatedProps={animatedProps} fill="none" stroke="red" strokeWidth="5" />
  </Svg>
);

我尝试在路径宽度上添加一些插值,但没有成功。我还尝试查看 Redash 的 interpolatePath() 实现,但它似乎采用两条路径作为输出范围。还有什么我应该看的吗?

标签: react-nativesvgreact-native-reanimatedreact-native-svgreact-native-reanimated-v2

解决方案


您需要使用useAnimatedStyle代替useAnimatedProps,并使用 计算组件(由 Animated 包装)的d值,基于您使用 0 更改为 1 的一些共享值。PathuseDerivedValueprogresswithTiming


推荐阅读