Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animating backgroundColor in React Native

How would I go about animating from one color to another in React Native. I've found that by interpolating an Animated.Value you can animate colors by:

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)'] }) 

and

Animated.timing(this.state.color, {toValue: RED}).start(); 

But using this method, going from BLACK to BLUE, you have to go through red. Add more colors to the mix and you end up in a 1980s disco.

Is there another way of doing this that allows you to go straight from one color to another?

like image 411
nicholas Avatar asked Sep 17 '15 04:09

nicholas


People also ask

How do you animate text color in React Native?

Put two text components (showing the same text) above each other (using absolute layout). You can then useNativeDriver and change the opacity of each text component. 2. Use react native reanimated v2 to change the color and archive native performance.

What is animated API in React Native?

Animated API​ Animated focuses on declarative relationships between inputs and outputs, with configurable transforms in between, and start / stop methods to control time-based animation execution.


2 Answers

Given you have Animated.Value lets say x, you can interpolate color like this:

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>     ); } 

You can find full working example in the issue I've posted on github.

like image 125
neciu Avatar answered Oct 25 '22 21:10

neciu


If you could get the color of the animated color value at the instant you pressed the button then you could probably do it. Something like this :

var currentColor = ? :  this.state.color = 0;  var bgColor = this.state.color.interpolate({   inputRange: [0, 1],   outputRange: [currentColor, targetColor] }); 

So for each button you'd set a different targetColor.

like image 44
cmrichards Avatar answered Oct 25 '22 19:10

cmrichards