繁体   English   中英

获取react-native中的主色?

[英]Get main color in react-native?

我正在使用 react-native 来构建我的应用程序,现在我面临一个 UI 模块的问题,需要我以编程方式获取图像的主颜色作为 UI 的背景。 我怎样才能用 react-native 方式制作它?

您可以尝试react-native-color-grabber 给定一个图像,返回占主导地位的 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'
    // }
});

如果您不具体获取图像的确切 colors 并且只想以与图像相同的配色方案在漂亮的背景中呈现图像(同时保持图像的纵横比),您可以通过使用解决此问题模糊效果并将模糊后面的图像加倍 ->

import {
  StyleSheet,
  Image,
  ImageBackground,
  Dimensions,
} from 'react-native';

/* components */
import {BlurView} from '@react-native-community/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,
  },
});

将会发生的是图像将包含自身并保持其纵横比,而背景图像将覆盖整个区域,并且模糊将为您提供图像配色方案的所需效果。

这是 iOS Gallery 应用程序中的默认行为。

使用可以使用这个奇妙的库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>

数据变量样本 output

{
  darkMuted: "#2a324b"
  darkVibrant: "#0e7a4b"
  lightMuted: "#9cceb7"
  lightVibrant: "#a4d4bc"
  muted: "#64aa8a"
  vibrant: "#b4d43c"
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM