Skip to content

RN Lez 31: Animated — Base

Docs: Animations, Animated

  • Creare animazioni con Animated.timing
  • Animare opacità e posizione
  • Usare useNativeDriver per performance

Animated permette di animare valori numerici che controllano proprietà UI.

import { Animated } from 'react-native';
const fadeAnim = useRef(new Animated.Value(0)).current;
// ↑ valore iniziale: 0

2. Animated.timing — animazione nel tempo

Section titled “2. Animated.timing — animazione nel tempo”
const FadeInView = ({ children }: { children: React.ReactNode }) => {
const fadeAnim = useRef(new Animated.Value(0)).current;
useEffect(() => {
Animated.timing(fadeAnim, {
toValue: 1, // valore finale
duration: 1000, // durata in ms
useNativeDriver: true, // ← IMPORTANTE: performance!
}).start();
}, [fadeAnim]);
return (
<Animated.View style={{ opacity: fadeAnim }}>
{children}
</Animated.View>
);
};

3. Proprietà animabili con useNativeDriver

Section titled “3. Proprietà animabili con useNativeDriver”

Con useNativeDriver: true puoi animare SOLO:

  • opacity
  • transform: translateX, translateY, scale, rotate

Non puoi animare: width, height, color, backgroundColor.


opacity: fadeAnim.interpolate({
inputRange: [0, 1],
outputRange: [0, 1],
})
const slideAnim = useRef(new Animated.Value(100)).current;
useEffect(() => {
Animated.timing(slideAnim, {
toValue: 0,
duration: 500,
useNativeDriver: true,
}).start();
}, []);
<Animated.View style={{
transform: [{ translateX: slideAnim }],
}}>
<Text>Scivola dentro!</Text>
</Animated.View>
const scaleAnim = useRef(new Animated.Value(0)).current;
useEffect(() => {
Animated.spring(scaleAnim, {
toValue: 1,
friction: 4, // ← meno attrito = più rimbalzo
useNativeDriver: true,
}).start();
}, []);
<Animated.View style={{
transform: [{ scale: scaleAnim }],
}} />

const scaleAnim = useRef(new Animated.Value(1)).current;
const premi = () => {
Animated.sequence([
Animated.timing(scaleAnim, { toValue: 0.9, duration: 100, useNativeDriver: true }),
Animated.timing(scaleAnim, { toValue: 1, duration: 100, useNativeDriver: true }),
]).start();
};
<Animated.View style={{ transform: [{ scale: scaleAnim }] }}>
<TouchableOpacity onPress={premi}>
<Text>Premi!</Text>
</TouchableOpacity>
</Animated.View>

MetodoCodice
Creare valorenew Animated.Value(0)
TimingAnimated.timing(val, {toValue, duration})
SpringAnimated.spring(val, {toValue, friction})
Avviare.start()
Native driveruseNativeDriver: true

Crea una card che all’avvio:

  1. Fade in (opacity: 0 → 1) in 1 secondo
  2. Slide up (translateY: 50 → 0) in 800ms con spring
  3. Scale (0.8 → 1) in 500ms con spring
  4. Le animazioni partono in parallelo

Usa Animated.parallel([...]).start().