首页 文章

React Native:完美地将文本对齐为圆圈

提问于
浏览
1

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

Horyzontally它很好,但无论我做什么,垂直对齐似乎都失败了 . 即使它在具有小fontSize的大cicle上看起来很好,小圆圈证明它是错误的!

<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,但我无法将文本(在本例中)正确地放在圆圈中 .

The + is not centered

Green background show it better

正如人们可以在图像上看到 <Text> -Component的绿色背景,文本不完全居中 . 即使它本身是完美对齐的......

这是世博会的小吃,整个代码减少到必要的和不同的示例尺寸:https://repl.it/@PaulHuchner/Centered-Text-in-Circles

1 回答

  • 1

    你试图将相同的 fontSizelineHeight 设置为圆的直径,其中包含 borderWidth10 .

    由于 borderWidth ,正在剪切文本并将其覆盖在圆圈上 . 分配给剪切 TextlineHeight 超出要求,因此显示 misaligned .

    因此,您需要根据圆的borderRadius减少 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

相关问题