I am use react-native to build my app and now i am facing an problem with an UI module which need me to get main color of an image programmatically as the background of UI. How can i make it with react-native way?
I am use react-native to build my app and now i am facing an problem with an UI module which need me to get main color of an image programmatically as the background of UI. How can i make it with react-native way?
Share Improve this question asked Sep 30, 2019 at 3:10 xiaoshitouxiaoshitou 6117 silver badges9 bronze badges 1- ps: the image is remote url with http not local assets – xiaoshitou Commented Sep 30, 2019 at 5:39
3 Answers
Reset to default 3You can try react-native-color-grabber . Given an image, returns dominant colors.
var colorGrabber = require('react-native').NativeModules.colorGrabber
colorGrabber.getColors(image, (err, res) => {
console.log(res);
// Returns:
// {
// 'UIDeviceRGBColorSpace 0.0784314 0.0941176 0.0823529 1': '0.1666667',
// 'UIDeviceRGBColorSpace 0.215686 0.203922 0.262745 1': '0.1666667',
// 'UIDeviceRGBColorSpace 0.517647 0.45098 0.380392 1': '0.6666667'
// }
});
If you're not specific in getting the exact colors of the image and are only looking to present the image in a nice background with the same color scheme as the image (while keeping the image's aspect ratio) you can work around this by using a blur effect and doubling the image in the back of the blur as so ->
import {
StyleSheet,
Image,
ImageBackground,
Dimensions,
} from 'react-native';
/* ponents */
import {BlurView} from '@react-native-munity/blur';
/* styles */
const {width} = Dimensions.get('window')
const DESIRED_HEIGHT = 200;
....
render() {
var {source} = this.props;
return (
<>
<ImageBackground style={[styles.containerStyle, styles.blur]} source={source}>
<BlurView
style={styles.containerStyle}
blurType="light"
blurAmount={10}
reducedTransparencyFallbackColor="white"
/>
</ImageBackground>
<Image style={styles.imageStyle} source={source} />
</>
);
}
const styles = StyleSheet.create({
containerStyle: {
height: DESIRED_HEIGHT,
width,
},
imageStyle: {
height: DESIRED_HEIGHT,
width,
resizeMode: 'contain',
},
blur: {
...StyleSheet.absoluteFillObject,
},
});
What will happen is that the image will contain itself and keep its aspect ratio while the background image will cover the whole area and the blur will give you the desired effect of the image's color scheme.
This is the default behavior in the iOS Gallery app.
Use can use this wonderful library react-palette
import { usePalette } from 'react-palette'
const { data, loading, error } = usePalette(IMAGE_URL)
<View style={{ backgroundColor: data.vibrant }}>
Text with the vibrant color
</View>
Sample output of data variable
{
darkMuted: "#2a324b"
darkVibrant: "#0e7a4b"
lightMuted: "#9cceb7"
lightVibrant: "#a4d4bc"
muted: "#64aa8a"
vibrant: "#b4d43c"
}