繁体   English   中英

如何将文字放在图像上

[英]How to put text over Image

所以我是新的反应原生(和一般的javascript),我正在努力实现这个目标:

在此输入图像描述

所以基本上这是一个带有文本的图像,但略微偏离图像顶部。

这就是我得到的: 我得到的

正如您所看到的那样,当文本不在图像中时,它不会被渲染。

这是我使用的代码:

class Test extends Component {
  render () {
    return (
      <View style={styles.matchContainer}>
        <Image source={ require('../../res/img/lol_wallpaper.jpg') } style={styles.backgroundImage}>
          <View style={styles.topContainer}>
            <Text style={styles.topText}>text</Text>
            <Text style={styles.topText}>text</Text>
          </View>
        </Image>
      </View>
    );
  }
}

这是css:

var styles = StyleSheet.create({
  matchContainer: {
    flexDirection: 'column',
    justifyContent: 'flex-start',
    width: width,
    height: 300,
    marginTop: 30,
    backgroundColor: '#FFFFFF',
  },
topText: {
    color: 'white',
    fontWeight: 'bold',
    backgroundColor: 'rgb(86, 203, 83)',

    padding: 2,
    position: 'relative',
  },
topContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginLeft: 5,
    marginRight: 5,
    marginBottom: 5,

    top: -10,
    position: 'relative',
  },
  backgroundImage: {
    width: width - 10,
    height: 138,
    marginLeft: 5,
    marginTop: 10,
    position: 'absolute',
  },
});

我怎样才能做到这一点?

谢谢 :)

我猜你为什么不能得到理想的答案,因为TextImage组件中。 因此,当某些部分超出图像时将无法显示。

我的方法是使用属性位置 我刚刚创建了一个简单的例子。 https://rnplay.org/apps/rpv82A

并记住react-native中的属性z-index取决于呈现顺序。 https://github.com/facebook/react-native/issues/698

您可以使用以下CSS属性来实现此目的:

position

通过使用此方法,您将只使用3个元素: divimgh2

HTML

<div class="img-box">
    <img src="http://science-all.com/images/wallpapers/league-of-legends-wallpaper/league-of-legends-wallpaper-20.jpg" />
    <h2>TEXT</h2>
</div>

CSS

.img-box {
margin-top: 50px;
width: 450px;
height: 200px;
position: relative;
}

.img-box img {
    width: 100%;
    height: auto;
}

.img-box h2 {
    width: 125px;
    height: 40px;
    position: absolute;
    top: -25%;
    left: 5%;
    font-size: 28pt;
    text-align: center;
    background-color: limegreen
}


尝试此代码后,您可以更改CSS中的值以满足您的需求,因为您尊重此结构。


 .img-box { margin-top: 50px; width: 450px; height: 200px; position: relative; } .img-box img { width: 100%; height: auto; } .img-box h2 { width: 125px; height: 40px; position: absolute; top: -25%; left: 5%; font-size: 28pt; text-align: center; background-color: limegreen } 
 <div class="img-box"> <img src="http://science-all.com/images/wallpapers/league-of-legends-wallpaper/league-of-legends-wallpaper-20.jpg" /> <h2>TEXT</h2> </div> 

暂无
暂无

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

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