渲染文本框与透明背景在React Native iOS中的图像顶部

Ste*_*lin 33 ios react-native

我正在尝试在我的React Native测试中在图像上渲染一个带有白色文本的块.但相反,我在我的图像上面有一个黑色的块,里面有白色文字.不是我所期待的.如何渲染透明背景的文本块?

目前的结果

在此输入图像描述

渲染功能

render: function(){
  return (
    <View style={styles.container}>
      <Image 
        style={styles.backdrop} 
        source={{uri: 'https://unsplash.com/photos/JWiMShWiF14/download'}}>
          <Text style={styles.headline}>Headline</Text>
      </Image>
    </View>
  );
)
Run Code Online (Sandbox Code Playgroud)

样式表功能

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-start',
    alignItems: 'center',
    backgroundColor: '#000000',
    width: 320
  },
  backdrop: {
    paddingTop: 60,
    width: 320,
    height: 120
  },
  headline: {
    fontSize: 20,
    textAlign: 'center',
    backgroundColor: 'rgba(0,0,0,0)',
    color: 'white'
  }
});
Run Code Online (Sandbox Code Playgroud)

Ste*_*lin 53

请注意:这个答案现在已经过时了.这适用于React Native在2015年开源的那一天.今天这种方式已被弃用.




您可以通过在View内部添加内容来实现此目的Image:

render: function(){
  return (
    <View style={styles.container}>
      <Image 
        style={styles.backdrop} 
        source={{uri: 'https://unsplash.com/photos/JWiMShWiF14/download'}}>
          <View style={styles.backdropView}>
            <Text style={styles.headline}>Headline</Text>
          </View>
      </Image>
    </View>
  );
)
Run Code Online (Sandbox Code Playgroud)

样式表功能

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-start',
    alignItems: 'center',
    backgroundColor: '#000000',
    width: 320
  },
  backdrop: {
    paddingTop: 60,
    width: 320,
    height: 120
  },
  backdropView: {
    height: 120,
    width: 320,
    backgroundColor: 'rgba(0,0,0,0)',
  },
  headline: {
    fontSize: 20,
    textAlign: 'center',
    backgroundColor: 'rgba(0,0,0,0)',
    color: 'white'
  }
});
Run Code Online (Sandbox Code Playgroud)


use*_*905 8

backgroundColor:'transparent' 这实际上是一种性能优化,而且非常具有攻击性.

" <Text>元素继承了它们的父<View>的背景颜色,但这种行为会导致更多烦恼,这在我看来很有用.一个简单的例子是带有嵌套<Text><Image >.文本节点将采用背景颜色或相反,父视图会隐藏图像.然后我们必须在文本节点上设置backgroundColor:'transparent'来修复它.

在Android上也不会发生此行为,默认情况下<Text>节点始终具有透明背景.这会在Android上开发一些东西然后在iOS上进行测试时会产生一些惊喜." - https://github.com/janicduplessis

这是来自用户将其作为问题提出的讨论.在这里阅读更多 - https://github.com/facebook/react-native/issues/7964

像Colin上面说的最简单的方法是将容器的backgroundColor设置为rgba(0,0,0,0)


Col*_*say 7

在内部,我看到React Native确实将alpha值和特殊情况transparent转换为具有alpha值的正确UIColor,因此这方面的工作正常,并且很容易通过实验验证.

请注意,如果backgroundColor将容器的容器设置为transparent(或rgba(0,0,0,0)),则还会获得透明文本块 - 该知识可帮助您解决此问题.但是我认为有可能将其解释为一个错误,因为这不是人们所期望的行为,感觉就像某种堆叠问题.