如何对react-native-svg多边形元素进行动画处理?

moh*_*arf 2 reactjs react-native react-native-svg

有没有一种简单的方法可以从react-native-svg库中对Polygon元素进行动画处理?我需要通过设置点的动画来设置他的形状的动画。我发现了一些关于如何为路径元素或圆形设置动画的示例,但找不到有关多边形的任何内容。提前致谢。

Fly*_*ets 5

聚会有点晚了,但如果你仍然感兴趣的话,我已经找到了解决方案。这并不完全“简单”,但它确实有效。有一个名为 React Native Reanimated 的库,它极大地扩展了动画组件的功能。这是我能够实现的目标:

在此输入图像描述

多边形动画无法开箱即用的原因是标准动画 API 只处理简单值,即单个数字。React-native-svg 中的 Polygon 组件采用点的 props,它是每个点的数组,它们本身是 x 和 y 的数组。例如:

<Polygon
        strokeWidth={1}
        stroke={strokeColour}
        fill={fillColour}
        fillOpacity={1}
        points={[[firstPointX, firstPointY],[secondPointX, secondPointY]}
 />
Run Code Online (Sandbox Code Playgroud)

React Native Reanimated 允许您对复杂的数据类型进行动画处理。在本例中,有 useSharedValue(其功能几乎与 new Animated.value() 相同)和一个名为 useAnimatedProps 的函数,您可以在其中创建点(或您想要设置动画的任何其他内容)并将它们传递给组件。

     // import from the library 
import Animated, {
      useSharedValue,
      useAnimatedProps,
    } from 'react-native-reanimated';

 // creates the animated component 
 const AnimatedPolygon = Animated.createAnimatedComponent(Polygon);

const animatedPointsValues = [
  {x: useSharedValue(firstXValue), y: useSharedValue(firstYValue)},
  {x: useSharedValue(secondXValue), y: useSharedValue(secondYValue)},
];

const animatedProps = useAnimatedProps(() => ({
      points: data.map((_, i) => {
        return [
          animatedPointValues[i].x.value,
          animatedPointValues[i].y.value,
        ];
      }),
    })),
Run Code Online (Sandbox Code Playgroud)

然后在你的渲染/返回中:

  <AnimatedPolygon
  strokeWidth={1}
        stroke={strokeColour}
        fill={fillColour}
        fillOpacity={1}
        animatedProps={animatedProps}
      />
Run Code Online (Sandbox Code Playgroud)

然后,每当您更新这些共享值之一时,该组件就会产生动画。

我建议阅读他们的文档并熟悉该库,因为它将打开一个充满可能性的世界:

https://docs.swmansion.com/react-native-reanimated/

此外,动画是在本机 UI 线程中处理的,很容易达到 60fps,但您可以用 JS 编写它们。

祝你好运!