React Native中Android端Text组件文本偏低且被裁切但iOS端显示正常
RN Text组件Android端垂直居中裁切问题适配
问题现状
- 预期效果:iOS端按钮内文字垂直居中、无裁切
- 实际效果:Android端文字位置偏低,上下边缘被裁切
现有代码
样式定义
text: { fontFamily: 'Roboto', fontSize: 40, width: 250, height: 40, textAlignVertical: 'center', textAlign: 'center', }, container: { backgroundColor: '#DDDDDD', width: 250, height: 55, margin: 12.5, borderRadius: 10, justifyContent: 'center' }
组件实现
<TouchableOpacity style={styles.container} onPress={_ => this.navigation.push('Join')} > <Text style={styles.text}>Join</Text> </TouchableOpacity> <TouchableOpacity style={styles.container} onPress={_ => this.navigation.push('Create')} > <Text style={styles.text}>Create</Text> </TouchableOpacity>
问题根因
Android端Text组件默认开启字形额外内边距,且默认行高大于fontSize;当前text样式给Text设置的height与fontSize完全相等,压缩了字形预留空间导致裁切。iOS端无该默认内边距逻辑,因此显示正常。
适配方案
方案1:移除Text固定高度,关闭Android字体内边距
删除text样式中的height: 40配置,新增仅Android生效的includeFontPadding: false属性,抵消默认内边距:text: { fontFamily: 'Roboto', fontSize: 40, width: 250, textAlign: 'center', textAlignVertical: 'center', ...Platform.select({ android: { includeFontPadding: false, } }) }配合容器的
justifyContent: 'center'即可实现两端效果一致。注意:使用
Platform.select前需先从react-native引入Platform模块。方案2:必须保留Text固定高度时,统一行高配置
若业务必须保留Text的固定高度,给两端设置统一的lineHeight,抵消Android默认行高差异:text: { fontFamily: 'Roboto', fontSize: 40, width: 250, height: 40, textAlign: 'center', lineHeight: 40, includeFontPadding: false, // 仅Android生效,iOS自动忽略 }方案3:分平台微调Android端行高
若上述方案仍有偏移,可单独给Android设置略大于fontSize的行高,数值根据实际效果微调(一般为fontSize的1.1~1.2倍):text: { fontFamily: 'Roboto', fontSize: 40, width: 250, height: 40, textAlign: 'center', ...Platform.select({ android: { lineHeight: 46, includeFontPadding: false, } }) }
内容的提问来源于stack exchange,提问作者firecraft gaming
相关产品推荐
相关产品推荐

