es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Reanimated(v2) con interpolación de translateY nativo.

Estoy tratando de crear una animación donde la barra roja se mueva a lo largo del eje y en una animación infinita y en reversa. Por alguna razón, no puedo entender y no puedo lograr el comportamiento deseado. Cualquier ayuda será muy apreciada.

“` js
import Animated, {
useAnimatedStyle,
useSharedValue,
interpolate,
withTiming,
withRepeat,
Extrapolate,
} from ‘react-native-reanimated’;

export default CustomMarker = () => {

const bar = useSharedValue(0);
const barStyle = useAnimatedStyle(() => {
const yValue = interpolate(bar.value, [0, 1], [0, 225]);
return {
transform: [{ translateY: yValue }],
};
});

useEffect(() => {
bar.value = withRepeat(withTiming(1, { duration: 800 }), -1, true);
});

return (


<animated.view style=”{[styles.redBarStyle,” barstyle]}=””></animated.view>


);

};

const styles = Stylesheet.create({
rectangleStyle: {
height: 230,
width: 400,
alignItems: ‘center’,
justifyContent: ‘center’,
},
redBarStyle: {
position: ‘absolute’,
top: 0,
height: 10,
width: 225,
backgroundColor: ‘red’,
borderRadius: 5,
},
})

Tags:  , , ,

Answer

  1. Avatar for davy.ai

    Para lograr una animación infinita y reversible donde la barra roja se mueve a lo largo del eje y, podemos modificar el hook useEffect para usar las funciones withRepeat y withSequence de react-native-reanimated. La función withRepeat repetirá la animación indefinidamente y la función withSequence invertirá la animación en cada segundo ciclo.

    Aquí está el código actualizado:

    import Animated, {
      useAnimatedStyle,
      useSharedValue,
      interpolate,
      withTiming,
      withRepeat,
      withSequence,
      Extrapolate,
    } from 'react-native-reanimated';
    
    export default CustomMarker = () => {
    
      const bar = useSharedValue(0);
      const barStyle = useAnimatedStyle(() => {
        const yValue = interpolate(bar.value, [0, 1], [0, 225]);
        return {
          transform: [{ translateY: yValue }],
        };
      });
    
      useEffect(() => {
        bar.value = withRepeat(
          withSequence(
            withTiming(1, { duration: 800 }),
            withTiming(0, { duration: 800 })
          ),
          -1, // -1 significa repetir indefinidamente
          true // true significa invertir cada segundo ciclo
        );
      }, []);
    
      return (
        <view style="{{" backgroundcolor:="" colors.darkoverlay,="" height:="" 540,="" alignitems:="" 'center',="" justifycontent:="" 'center',="" }}="">
          <view style="{styles.rectangleStyle}">
            <animated.view style="{[styles.redBarStyle," barstyle]}=""></animated.view>
          </view>
        </view>
      );
    };
    
    const styles = StyleSheet.create({
      rectangleStyle: {
        height: 230,
        width: 400,
        alignItems: 'center',
        justifyContent: 'center',
      },
      redBarStyle: {
        position: 'absolute',
        top: 0,
        height: 10,
        width: 225,
        backgroundColor: 'red',
        borderRadius: 5,
      },
    });
    

    En el código actualizado, hemos agregado la función withSequence para encadenar dos animaciones withTiming juntas. La primera animación establece el valor en 1 en 800ms, y la segunda animación establece el valor en 0 en 800ms. La función withRepeat luego repite esta secuencia indefinidamente e invierte la dirección en cada segundo ciclo. Finalmente, agregamos un arreglo de dependencias vacío al hook useEffect para asegurarnos de que se ejecute solo una vez.

    Con estos cambios, la barra roja debería moverse hacia arriba y hacia abajo en el eje y indefinidamente e invertir su dirección cada segundo ciclo.

Comments are closed.