[英]Animating backgroundColor in React Native
我 go 如何在 React Native 中將動畫從一種顏色轉換為另一種顏色。 我發現通過插入 Animated.Value 可以通過以下方式為 colors 設置動畫:
var BLACK = 0;
var RED = 1;
var BLUE = 2;
backgroundColor: this.state.color.interpolate({
inputRange: [BLACK, RED, BLUE],
outputRange: ['rgb(0, 0, 0)', 'rgb(255, 0, 0)', 'rgb(0, 0, 255)']
})
和
Animated.timing(this.state.color, {toValue: RED}).start();
但是使用這種方法,從黑色到藍色,你必須通過紅色到 go。 添加更多 colors 到混音中,您將進入 1980 年代的迪斯科舞廳。
有沒有另一種方法可以讓你 go 直接從一種顏色到另一種顏色?
假設您有Animated.Value
可以說x
,您可以像這樣插入顏色:
render() {
var color = this.state.x.interpolate({
inputRange: [0, 300],
outputRange: ['rgba(255, 0, 0, 1)', 'rgba(0, 255, 0, 1)']
});
return (
<Animated.View style={{backgroundColor:color}}></Animated.View>
);
}
您可以在我發布在github上的問題中找到完整的工作示例。
如果您可以在按下按鈕的那一刻獲得動畫顏色值的顏色,那么您可能可以做到。 像這樣的東西:
var currentColor = ? :
this.state.color = 0;
var bgColor = this.state.color.interpolate({
inputRange: [0, 1],
outputRange: [currentColor, targetColor]
});
因此,對於每個按鈕,您需要設置不同的 targetColor。
我在這里創建了一個示例,應該如何使用最新版本的 react native 來做到這一點。
https://cjoshmartin.com/blog/react-native-animations-example/
您還可以在此處閱讀更多信息: https ://www.codedaily.io/courses/Master-React-Native-Animations/Color-Background-Color https://reactnative.dev/docs/animations
通過在末尾復制第一種顏色,設法阻止我在循環中閃爍:
const backgroundColourIndex = useRef(new Animated.Value(0)).current;
let backgroundColorAnimated = backgroundColourIndex.interpolate({
inputRange: [0, 1, 2, 3],
outputRange: ['red', 'blue', 'yellow', 'red'],
});
const animatedBkg = interpolate(scale, {
inputRange: [0, 150],
outputRange: [Animated.color(242, 81, 48), Animated.color(0,0,0)],
// extrapolate: Extrapolate.CLAMP,
})
測試與復活。
對於顏色等非數字值,您還可以分步進行插值,如下所示:
<Animated.Text
style={{
color: colorAnim.interpolate({
inputRange: [0, 0.5, 1],
outputRange: ['black', 'gray', 'white']
})
}}>
使用setValue
和 state 來控制開始和結束顏色。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.