【问题标题】:React Native place a text over SVG imageReact Native 在 SVG 图像上放置一个文本
【发布时间】:2021-01-07 18:49:03
【问题描述】:

我正在使用库:“react-native-svg”:“12.1.0”和“react-native-svg-transformer”:“0.14.3”

import FooIcon from '../assets/images/icons/fooIcon.svg';

<View style={{ flex: 1, paddingTop: 8 }}>
   <FooIcon></FooIcon>
   <View style={{ position: 'absolute', top: 35, bottom: 0, left: 14, right: 0 }} >
      <Text>foo</Text>
   </View>
</View>

如何将“foo”文本置于 FooIcon 的中心。上面的解决方案没有使文本居中,这很重要,因为“foo”文本长度可以改变,并且在每种情况下都必须居中。

【问题讨论】:

    标签: javascript css react-native svg


    【解决方案1】:

    这段代码应该可以为您完成工作

        <View
        style={{
          justifyContent: 'center',
          alignItems: 'center'
        }}
        >
        <SVG /> //your svg image component goes here
        <Text
          style={{
            position: 'absolute'
          }}
        >
          Test
        </Text>
      </View>
    

    【讨论】:

      【解决方案2】:

      如果内容大小可以动态变化,我建议不要使用绝对位置。我将只使用 flex-box 来构建它:

      ...
      <View style={styles.itemContainer}>
        <Text>Foo</Text>
        <View style={styles.iconMock} />
      </View>
      ...
      const styles = StyleSheet.create({
        itemContainer: {
          alignItems: "center",
          //this has default flex: 0, which means the container will always have the size the children take.
          //we then tell it to centre all the children (items) which gives the needed effect.
        },
        iconMock: {
          backgroundColor: "blue",
          height: 50,
          width: 150,
        }
      });
      

      以这种方式构建文本将始终居中:

      【讨论】:

      • 对不起,我的意思是 Foo 应该在蓝色方块上。就在中间。
      • 请查看我添加的示例图片。
      猜你喜欢
      • 1970-01-01
      • 2019-08-11
      • 1970-01-01
      • 2016-02-19
      • 2014-09-24
      • 2021-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多