Here is piece of animated style code for a pinch action with React Native gesture handler 2.x/React Native reanimated 2.x.
export default Swipe = ({route, navigation}) => {
const { width, height } = Dimensions.get("window");
const translationX = useSharedValue(0);
const translateX = useSharedValue(0);
//pinch
const scale = useSharedValue(1);
const focalX = useSharedValue(0);
const focalY = useSharedValue(0);
const pinch = useMemo(() => Gesture.Pinch()
.onUpdate((event) => {
//console.log("pinch event : ", event);
scale.value = event.scale;
focalX.value = event.focalX;
focalY.value = event.focalY;
})
.onEnd((event) => {
scale.value = withTiming(1);
})
.simultaneousWithExternalGesture(pan) //work together with pan gesture
);
const pinchStyle = useAnimatedStyle(() => {
return {
transform: [
{ translateX: focalX.value },
{ translateY: focalY.value },
{ translateX: -width / 2 }, //<<===defined again
{ translateY: -height / 2 }, //<<==defined again
{ scale: scale.value },
{ translateX: -focalX.value }, //<<==
{ translateY: -focalY.value }, //<<==
{ translateX: width / 2 }, //<<==
{ translateY: height / 2 }, //<<==
],
};
}, []);
}
I am not an expert on animation and not sure why both translateX and translateY were defined multiple times in pinchStyle
. Is it describing a animated process with element starting with position at focalX/focalY, move to -width/2/-height/2, and scale (to scale.value), then to -focalX/-focalY and ends up back to the center of the screen (width/2/height/2)?