Using React Native with Expo. Having difficulties centering custom imported font, at iOS. Android rendering with no issues, the text is vertically centered perfectly. Using iOS it is slightly upper than the center.
(Native Font centering well on both emulators - Android and iOS).
Any ideas how this could be solved?
Code below:
import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Font } from 'expo';
export default class extends Component {
constructor(props) {
super(props);
this.state = {
isReady: false
};
}
async componentDidMount() {
await Font.loadAsync({
'KlavikaBold': require('./KlavikaBold.otf'),
});
this.setState({ isReady: true });
}
render() {
if (!this.state.isReady) {
return <Expo.AppLoading />;
}
return (
<View style={styles.container}>
<Text style={styles.content}>Home!</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
content: {
backgroundColor: 'green',
color: 'white',
padding: 10,
textAlignVertical: 'center',
fontFamily: 'KlavikaBold',
fontSize: 20,
}
})
To put a Text component vertically and horizontally center of View component in RN we have to use justifyContent: 'center' and alignItems: 'center' layout styles.
To center a component horizontally and vertically in React. js, set its display property to flex and its alignItems and justifyContent properties to center . The components's content will be horizontally and vertically centered. Copied!
On iOS textAlignVertical: 'center'
has no effect, but you can achieve a similar result when setting the lineHeight
to the doubled height of the fontSize
.
We only need to apply the doubled lineHeight on iOS, therefore we import Platform
import { StyleSheet, Text, View, Platform } from 'react-native'; // add Platform at the beginning
and then change the following:
<Text style={[styles.content, {lineHeight: Platform.OS === 'ios' ? 40 : 20 }]}>Home!</Text>
Here's an easy solution that worked for me...
- Download Font Tools for Xcode
- In Terminal run $ ftxdumperfuser -t hhea -A d pathtoyourfont.ttf
- Edit dumped pathtoyourfont.hhea.xml and set lineGap="0"
- If lineGap was 200 and ascender="800", set ascender to the sum ot these two 1000
- In Terminal run $ ftxdumperfuser -t hhea -A f pathtoyourfont.ttf
Done. Your new values are fused back the font file.
Repeat steps 4 and 5 until the rendering is OK. Do not change other values. Those should be OK.
Value that finally worked for me was ascender="1050". Try to change the sum until Android and iOS render the component the same height.
Source: https://medium.com/@martin_adamko/consistent-font-line-height-rendering-42068cc2957d
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With