【问题标题】:I'm trying to animate a circle expanding, staying at maximum width and height for 4 seconds, then shrink again to original size, then repeat again我正在尝试为一个圆圈制作动画,该圆圈在最大宽度和高度保持 4 秒,然后再次缩小到原始大小,然后再次重复
【发布时间】:2022-12-14 01:07:18
【问题描述】:

我正在尝试为一个 120px 的圆圈设置动画以在 4 秒内扩展到 255px,然后在 255px 停留 4 秒,然后在 4 秒内开始缩小到 120px。然后无限期地重复这个。

目前我已经确定了扩展部分,但我无法弄清楚如何将它保持在最大宽度/高度 4 秒然后将其缩小。

这是一个 Expo Snack,展示了我到目前为止所做的以及它是如何工作的 - https://snack.expo.dev/@bozhidark/frowning-cookie

import React, { FunctionComponent, useEffect } from 'react';
import Animated, {
    useAnimatedStyle,
    useSharedValue,
    withDelay,
    withRepeat,
    withSpring,
    withTiming,
} from 'react-native-reanimated';
import styled from 'styled-components/native';

const BreatheAnimation: FunctionComponent<Props> = () => {
    const widthAndHeight = useSharedValue(120);
    const breathLength = 4;

    const foregroundCircleStyle = useAnimatedStyle(() => {
        return {
            width: widthAndHeight.value,
            height: widthAndHeight.value,
            borderRadius: widthAndHeight.value / 2,
        };
    });

    useEffect(() => {
        widthAndHeight.value = withDelay(
            4000,
            withRepeat(
                withTiming(255, {
                    duration: breathLength * 1000,
                }),
                -1,
                false
            )
        );
    }, [breathLength, widthAndHeight]);

    return (
        <BackgroundCircle>
            <ForegroundCircle style={[foregroundCircleStyle]} />
        </BackgroundCircle>
    );
};

const BackgroundCircle = styled.View`
    display: flex;
    justify-content: center;
    align-items: center;
    width: 255px;
    height: 255px;
    border-radius: 122px;
    background-color: red;
    position: absolute;
    top: 300px;
`;

const ForegroundCircle = styled(Animated.View)`
    width: 120px;
    height: 120px;
    border-radius: 60px;
    background-color: yellow;
`;

export default BreatheAnimation;

【问题讨论】:

    标签: javascript reactjs react-native react-native-reanimated react-native-reanimated-v2


    【解决方案1】:

    我将您的效果重构为如下所示:

    useEffect(() => {
        widthAndHeight.value = withRepeat(
          withSequence(
            withTiming(255, { duration: breathLength * 1000 }),
            withDelay(4000, withTiming(120, { duration: breathLength * 1000 }))
          ),
          -1
        );
      }, [breathLength, widthAndHeight]);
    

    它似乎像你描述的那样工作。

    解释代码:

    首先,你想永远重复某个动画,所以你用 withRepeat 函数包装动画,将 -1 作为第二个参数传递。

    您要重复的动画是两个动画的序列:

    • 扩大圆圈超过 4 秒 (withTiming);
    • 等待4秒(withDelay),将圆圈缩小(withTiming);

    另外,与动画无关,但如果你想要一个完美的圆,你的border-radius 应该至少是width(或height,因为它们是一样的)除以 2,所以至少 ~128px。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      相关资源
      最近更新 更多