Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: Perfectly align Text in circle

I have a circle button (made with borderRadius) in React Native. The text in the component should be centered both vertically and horizonatlly.

Horyzontally it's fine, but the vertical alignment seems to fail whatever I do. Even if it looks good on large cicles with small fontSize, the small circles proof it wrong!

        <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>

Although already answered elsewhere, I'm unable to center text (in this case) in a circle properly.

The + is not centeredGreen background show it better

As one can see on the image with the green background of the <Text>-Component, the text is just not centered perfectly. Even though the itself is perfecttly aligned...

Here is a snack for Expo with the whole code reduced to the necessary and with different example sizes: https://repl.it/@PaulHuchner/Centered-Text-in-Circles

like image 762
Pauloco Avatar asked Apr 28 '18 16:04

Pauloco


2 Answers

I have tried the previous answer with only Text and calculating line-height. which looks like a little overkill and didn't work for me. So here's my answer.

I am using View as the container with 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>
like image 102
Tilak Puli Avatar answered Sep 28 '22 15:09

Tilak Puli


You're trying to set the same fontSize and lineHeight as the circle's diameter, which has borderWidth of 10 included to it.

Due to the borderWidth, the text is being cut and overlayed over the circle. The lineHeight assigned to the cut Text is more than required, hence it is displayed misaligned.

Therefore you need to reduce the fontSize and the lineHeight based on the borderRadius of the circle, to function properly for all dimensions.

<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
   }}>

Here's a snack link

like image 45
Pritish Vaidya Avatar answered Sep 28 '22 15:09

Pritish Vaidya