今天用了一天的react-native-renimated2,这玩意确实强大,对插值一直没详细研究过,今天用到一个动画,不得不用插值,就详细看了下,demo如下
import React from "react";
import { View, StyleSheet, Dimensions } from "react-native";
import Animated, {
useSharedValue,
useAnimatedScrollHandler,
useAnimatedStyle,
interpolate,
Extrapolate,
} from "react-native-reanimated";
import { t } from "react-native-tailwindcss";
export const HEADER_IMAGE_HEIGHT = Dimensions.get("window").width / 3;
export default function Dashboard() {
const scrollY = useSharedValue(0);
const scrollHandler = useAnimatedScrollHandler({
onScroll: (e) => {
scrollY.value = e.contentOffset.y;
console.log("====================================");
console.log(scrollY.value);
console.log("====================================");
},
});
const animatedStyles = useAnimatedStyle(() => {
const scale = interpolate(scrollY.value, [100, 0], [3, 1], {
extrapolateRight: Extrapolate.CLAMP,
});
return {
transform: [{ scale: scale }],
};
});
return (
<View
style={[{ flex: 1, alignItems: "center" }, t.bgRed300, t.wFull, t.hFull]}
>
<Animated.View
style={[
{
position: "absolute",
top: 90,
left: 20,
width: 20,
height: 20,
backgroundColor: "blue",
},
animatedStyles,
]}
/>
<Animated.ScrollView
scrollEventThrottle={1}
style={StyleSheet.absoluteFill}
onScroll={scrollHandler}
>
{[0, 1, 2, 3, 43, 4, 45, 45, 45, 46, 432, 22, 333].map(() => (
<View style={[t.h48]} />
))}
</Animated.ScrollView>
</View>
);
}
其中关键是
const scale = interpolate(scrollY.value, [-100, 0], [3, 1], {
extrapolateRight: Extrapolate.CLAMP,
});
这段代码我看了好久才搞明白,插值依赖的是scrollY.value
,所以inputrange: [-100, 0],outputrange:[3,1]对应的就是当scrollY.value的值为-100的时候,scale的值就是3,当0的时候scale就是1,效果如下:

可以清晰看到,y的值在0到-100之间,scale的值都是1,当y<-100时候,scale变为成y/100=scale/3,这样算出来的scale
网友评论