Changing colors, and opacity of colors (using rgba) is another common animation in an application. You must use interpolate
to animate between colors. Animated
has special interpolations built in to be able to identify colors, and generic numeric patterns.
Using animated for colors will only work for rbg/rgba/hcl
it will not work for hex
colors. So if you want to animate a color you'll need to convert your hex to one of the formats interpolation allows.
Lets look at 2 cases. RGB and RGBA interpolations.
export default class animations extends Component { state = { animation: new Animated.Value(0), }; componentDidMount() { Animated.timing(this.state.animation, { toValue: 1, duration: 1000, }).start(); } render() { const bgStyle = { backgroundColor: this.state.animation.interpolate({ inputRange: [0, 1], outputRange: ["rgba(255,99,71, 1)", "rgba(255,99,71, 0)"], }), }; const boxStyle = { backgroundColor: this.state.animation.interpolate({ inputRange: [0, 1], outputRange: ["rgb(99,71,255)", "rgb(255,99,71)"], }), }; return ( <Animated.View style={[styles.container, bgStyle]}> <Animated.View style={[styles.box, boxStyle]} /> </Animated.View> ); } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: "center", justifyContent: "center", }, box: { height: 100, width: 100, }, });
We have 2 interpolations here. One for our outside and one for our box. They both start at the same color. The background though is the same color, however we only interpolate the alpha of the RGBA. So it will animate the opacity. Then we also animate our box from a blue-purple to the tomato background color.
This is just demonstrating that interpolate
doesn't care about the values, it will figure it all out correctly.