在 React Native 中添加自定义字体后的文本对齐问题 - iOS 与 Android

问题描述 投票:0回答:1

我最近向我的 React Native 项目添加了自定义字体,并且在文本组件中的边界框中遇到了文本对齐问题。

在 iOS 设备上,文本看起来向上移动到边界框的顶部边框,而在 Android 设备上,文本正确对齐到中心。

下面是代码以及相应的 iOS 和 Android 输出:

import { useFonts } from "expo-font";
import * as SplashScreen from "expo-splash-screen";
import React, { useCallback } from "react";
import { Text, View, StyleSheet } from 'react-native';

SplashScreen.preventAutoHideAsync();

export default function App() {
  const [fontsLoaded, fontError] = useFonts({
    mainReg: require("./assets/fonts/DINNextRoundedLTPro-Regular.otf"),
    mainMed: require("./assets/fonts/DINNextRoundedLTPro-Medium.otf"),
    mainBold: require("./assets/fonts/DINNextRoundedLTPro-Bold.otf"),
  });

  const onLayoutRootView = useCallback(async () => {
    if (fontsLoaded || fontError) {
      await SplashScreen.hideAsync();
    }
  }, [fontsLoaded, fontError]);

  if (!fontsLoaded && !fontError) {
    return null;
  }

  return (
    <View style={styles.container} onLayout={onLayoutRootView}>
      <View style={styles.box}>
        <Text style={styles.text}>TEXT</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
  },
  box: {
    margin: 10,
    height: 60,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "lightblue",
  },
  text: {
    fontFamily: "mainBold",
    fontSize: 44,
    //textAlign: "center",
    backgroundColor: "red",
  },
});

我尝试过调整样式和对齐方式,但我似乎无法解决 iOS 和 Android 之间的这种差异。

有人可以提供有关如何在 React Native 中添加自定义字体后确保 iOS 和 Android 平台上文本对齐一致的见解或建议吗?任何帮助或指示将不胜感激。

javascript react-native fonts expo
1个回答
0
投票

你的字体有填充

    {
      // fixed style
      includeFontPadding: false,
      verticalAlign: 'middle',
      textAlign: 'left',
      // writingDirection: testArabic ? 'rtl' : 'ltr',
      lineHeight: hp(3.2),
      textAlignVertical: 'center',
    },
© www.soinside.com 2019 - 2024. All rights reserved.