【问题标题】:React Native: Perfectly align Text in circleReact Native:将文本完美对齐
【发布时间】:2018-10-09 05:59:43
【问题描述】:

我在 React Native 中有一个圆形按钮(使用 borderRadius 制作)。组件中的文本应垂直和水平居中。

水平方向很好,但无论我做什么,垂直对齐似乎都失败了。即使它在具有小字体大小的大圆圈上看起来不错,但小圆圈证明它是错误的!

        <View style = {{
          alignItems:'center', 
          justifyContent:'center',  
          backgroundColor:'yellow', 
          borderColor: this.props.color,    
          width:size,   height:size, 
          borderRadius:size, 
          borderWidth:borderWidth,
        }}>
            <Text style = {{
              textAlign: 'center',  
              backgroundColor:'none', 
              fontSize:fontSize, 
              lineHeight:fontSize,
            }}>
              {this.props.title}
            </Text>
        </View>

虽然已经回答了elsewhere,但我无法将文本(在这种情况下)正确地居中。

正如您在&lt;Text&gt;-Component 的绿色背景图像上看到的那样,文本没有完全居中。即使它本身是完美对齐的......

这里是 Expo 的小吃,整个代码减少到必要的大小,并具有不同的示例大小:https://repl.it/@PaulHuchner/Centered-Text-in-Circles

【问题讨论】:

    标签: react-native vertical-alignment


    【解决方案1】:

    我已经尝试了仅使用文本和计算行高的上一个答案。这看起来有点矫枉过正,对我不起作用。所以这是我的答案。

    我使用 View 作为 justifyContent:center 的容器

    <View style={{
    width: 40,
    height: 40,
    
    borderRadius: 20,
    borderWidth: 1,
    borderColor: 'black',
    borderStyle: 'solid',
    
    justifyContent: 'center'}}>
     <Text style={{fontSize: 20,textAlign: 'center'}}>20</Text></View>
    

    【讨论】:

      【解决方案2】:

      您尝试将fontSizelineHeight 设置为圆的直径,其中包含borderWidth10

      由于borderWidth,文本被剪切并覆盖在圆圈上。分配给剪切TextlineHeight 超出了要求,因此显示为misaligned

      因此,您需要根据圆的边框半径减少fontSizelineHeight,以便在所有维度上正常工作。

      <Text style = {{
           textAlign: 'center',
           backgroundColor:'green',
           fontSize:fontSize - 2 * borderWidth, //... One for top and one for bottom alignment
           lineHeight:fontSize - (Platform.OS === 'ios' ? 2 * borderWidth : borderWidth), //... One for top and one for bottom alignment
         }}>
      

      这是点心link

      【讨论】:

      • 感谢您的快速答复!实际上这也不能解决它:(我不在乎文本是否超出圆圈,只要它居中即可。我用你的更改做了点心:repl.it/@PaulHuchner/Centered-Text-in-Circles-1
      • 你的零食也不适合我 :( 看起来 like this: 现在字母太高了。这只是我的设备吗?
      • 您是否在 android 上进行测试,因为我还没有看到。在 android 上可能会有不同的行为。
      • 是的,还有模拟器的零食显示它像 android :( 还有其他想法吗?看起来,问题在于 -Component 中字体的对齐方式跨度>
      • 你是最棒的!看起来很完美。 S
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 2018-02-22
      • 2016-07-29
      • 1970-01-01
      相关资源
      最近更新 更多