React Native 我怎么能使用透明的背景,如果我得到的颜色代码作为十六进制数从消防基地

1wnzp6jl  于 2023-04-07  发布在  React
关注(0)|答案(1)|浏览(174)

我从Firebase得到颜色数据就像这样
“颜色”:“#E5E1FF”
我用颜色来代表风格

style={[styles.addItem, { backgroundColor: item.color }]}

在这种情况下,如何调整背景透明度?

ego6inou

ego6inou1#

将十六进制转换为rgba(Convert Hex to RGBA
我的example:

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';

// You can import from local files
import AssetExample from './components/AssetExample';

// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
function hexToRgbA(hex, alpha = 1) {
  var c;
  if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) {
    c = hex.substring(1).split('');
    if (c.length == 3) {
      c = [c[0], c[0], c[1], c[1], c[2], c[2]];
    }
    c = '0x' + c.join('');
    return (
      'rgba(' +
      [(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',') +
      ',' +
      alpha +
      ')'
    );
  }
  throw new Error('Bad Hex');
}

export default function App() {
  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>
        Change code in the editor and watch it change on your phone! Save to get
        a shareable url.
      </Text>
      <Card style={{backgroundColor: hexToRgbA('#ff0000',0.5)}}> {/*second parameter of hexToRgbA define the transparency*/}
        <AssetExample />
      </Card>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

相关问题