react-native-skiaでテキストにLinearグラデーションを付けるには以下のようにします。<Text>
のchildrenに<LinearGradient />
を指定するだけです。
<Text x={pos.x} y={pos.y} font={font} text="Gradient Text by Skia">
<LinearGradient
start={{ x: 0, y: 100 }}
end={{ x: window.width, y: 100 }}
colors={["#863FFF", "#FF84D0"]}
positions={positions}
/>
</Text>
ついでにグラデーションが横に移動していくようなアニメーションを設定してみます。
LinearGradient
にはpositions
propが存在しますが、これはグラデーションの各ポイントのポジションを0から1の間で指定するものです。この値を動的に変更させます。
繰り返しのアニメーションを指定したアニメーションvalueを用意し
const progress = useSharedValue(0)
useEffect(() => {
progress.value = withRepeat(
withTiming(1, {
easing: Easing.inOut(Easing.ease),
duration: 2500,
}),
-1,
false,
)
}, [])
useDerivedValue
でグラデーションの3つのポイントが移動していくように変化させます。
const positions = useDerivedValue(() => {
return [
interpolate(progress.value, [0, 0.25, 0.5, 0.75, 1], [0, 0, 0, 0.5, 1]),
interpolate(progress.value, [0, 0.25, 0.5, 0.75, 1], [0, 0, 0.5, 1, 1]),
interpolate(progress.value, [0, 0.25, 0.5, 0.75, 1], [0, 0.5, 1, 1, 1]),
]
}, [])
<LinearGradient
...
colors={["#863FFF", "#FF84D0", "#863FFF"]}
positions={positions}
/>
コード全体はこちらで確認できます。react-native-skiaのおかげでかなり少ないコード量で実現できるのが実感できます。
アニメーションをかける部分で以下のライブラリのコードを参考にしました。 FullstackStation/react-native-svg-animated-linear-gradient