繁体   English   中英

React Native 响应式字体大小

[英]React Native Responsive Font Size

我想问一下如何反应原生句柄或做响应式字体。 例如在 iphone 4s 我有 fontSize: 14,而在 iphone 6 我有 fontSize: 18。

您可以使用PixelRatio

例如:

var React = require('react-native');

var {StyleSheet, PixelRatio} = React;

var FONT_BACK_LABEL   = 18;

if (PixelRatio.get() <= 2) {
  FONT_BACK_LABEL = 14;
}

var styles = StyleSheet.create({
  label: {
    fontSize: FONT_BACK_LABEL
  }
});

编辑:

另一个例子:

import { Dimensions, Platform, PixelRatio } from 'react-native';

const {
  width: SCREEN_WIDTH,
  height: SCREEN_HEIGHT,
} = Dimensions.get('window');

// based on iphone 5s's scale
const scale = SCREEN_WIDTH / 320;

export function normalize(size) {
  const newSize = size * scale 
  if (Platform.OS === 'ios') {
    return Math.round(PixelRatio.roundToNearestPixel(newSize))
  } else {
    return Math.round(PixelRatio.roundToNearestPixel(newSize)) - 2
  }
}

用法:

fontSize: normalize(24)

您可以通过允许按预定义大小在每个<Text />组件上使用大小来更进一步。

例子:

const styles = {
  mini: {
    fontSize: normalize(12),
  },
  small: {
    fontSize: normalize(15),
  },
  medium: {
    fontSize: normalize(17),
  },
  large: {
    fontSize: normalize(20),
  },
  xlarge: {
    fontSize: normalize(24),
  },
};

我们使用我们编写的简单、直接、可扩展的 utils 函数:

import { Dimensions } from 'react-native';
const { width, height } = Dimensions.get('window');

//Guideline sizes are based on standard ~5" screen mobile device
const guidelineBaseWidth = 350;
const guidelineBaseHeight = 680;

const scale = size => width / guidelineBaseWidth * size;
const verticalScale = size => height / guidelineBaseHeight * size;
const moderateScale = (size, factor = 0.5) => size + ( scale(size) - size ) * factor;

export {scale, verticalScale, moderateScale};

为您节省一些时间做许多如果。 您可以在我的博客文章中阅读更多相关信息。


编辑:我认为将这些函数提取到他们自己的 npm 包中可能会有所帮助,我还在包中包含了ScaledSheet ,它是StyleSheet的自动缩放版本。 你可以在这里找到它: react-native-size-matters

adjustsFontSizeToFitnumberOfLines对我有用。 他们将长电子邮件调整为 1 行。

<View>
  <Text
    numberOfLines={1}
    adjustsFontSizeToFit
    style={{textAlign:'center',fontSize:30}}
  >
    {this.props.email}
  </Text>
</View>

因为响应式单元目前在 react-native 中不可用,我想说你最好的选择是检测屏幕尺寸,然后使用它来推断设备类型并有条件地设置 fontSize。

您可以编写如下模块:

function fontSizer (screenWidth) {
  if(screenWidth > 400){
    return 18;
  }else if(screenWidth > 250){
    return 14;
  }else { 
    return 12;
  }
}

您只需要查看每个设备的默认宽度和高度。 如果在设备改变方向时宽度和高度被翻转,您可能可以使用纵横比,或者只计算两个维度中较小的一个来计算宽度。

模块模块可以帮助您查找设备尺寸或设备类型。

我通过执行以下操作设法克服了这个问题。

  1. 为您拥有的当前视图选择您喜欢的字体大小(确保它看起来适合您在模拟器中使用的当前设备)。

  2. import { Dimensions } from 'react-native'并定义组件外部的宽度,如下所示: let width = Dimensions.get('window').width;

  3. 现在 console.log(width) 把它写下来。 例如,如果你好看的字体大小是 15,宽度是 360,那么取 360 除以 15(= 24)。 这将是适应不同尺寸的重要价值。

    在您的样式对象中使用此数字,如下所示: textFontSize: { fontSize = width / 24 },...

现在你有了一个响应式 fontSize。

看看我写的库: https ://github.com/tachyons-css/react-native-style-tachyons

它允许您在启动时指定 root-fontSize ( rem ),您可以根据PixelRatio或其他设备特性进行设置。

然后你得到相对于你的rem的样式,不仅是 fontSize,还有 paddings 等:

<Text style={[s.f5, s.pa2, s.tc]}>
     Something
</Text>

扩展:

  • f5始终是您的基本字体大小
  • pa2为您提供相对于基本字体大小的填充。
import { Dimensions } from 'react-native';

const { width, fontScale } = Dimensions.get("window");

const styles = StyleSheet.create({
    fontSize: idleFontSize / fontScale,
});

fontScale根据您的设备获取比例

我只是使用屏幕尺寸的比例,这对我来说很好。

const { width, height } = Dimensions.get('window');

// Use iPhone6 as base size which is 375 x 667
const baseWidth = 375;
const baseHeight = 667;

const scaleWidth = width / baseWidth;
const scaleHeight = height / baseHeight;
const scale = Math.min(scaleWidth, scaleHeight);

export const scaledSize =
    (size) => Math.ceil((size * scale));

测试

const size = {
    small: scaledSize(25),
    oneThird: scaledSize(125),
    fullScreen: scaledSize(375),
};

console.log(size);

// iPhone 5s
{small: 22, oneThird: 107, fullScreen: 320}
// iPhone 6s
{small: 25, oneThird: 125, fullScreen: 375}
// iPhone 6s Plus
{small: 28, oneThird: 138, fullScreen: 414}

我们可以使用 flex 布局并使用 adjustsFontSizeToFit={true} 来获得响应式字体大小。并且文本会根据容器的大小进行调整。

     <Text
    adjustsFontSizeToFit
    style={styles.valueField}>{value}
    </Text>

但是在样式中,您还需要放置一个字体大小,然后adjustsFontSizeToFit 才会起作用。

    valueField: {
    flex: 3,
    fontSize: 48,
    marginBottom: 5,
    color: '#00A398',
},

我最近遇到了这个问题并最终使用了react-native-extended-stylesheet

您可以根据屏幕尺寸设置rem值和附加尺寸条件。 根据文档:

// component
const styles = EStyleSheet.create({
  text: {
    fontSize: '1.5rem',
    marginHorizontal: '2rem'
  }
});
// app entry
let {height, width} = Dimensions.get('window');
EStyleSheet.build({
  $rem: width > 340 ? 18 : 16
});

为什么不使用PixelRatio.getPixelSizeForLayoutSize(/* size in dp */); , 它与 Android 中的pd单位相同。

我通常使用这个:

import React from 'react';
import { View, Text, StyleSheet, Dimensions } from 'react-native';

var heightY = Dimensions.get("window").height;

export default function App() {
  return (
    <View style={styles.container}>
      <Text style={styles.textStyle}>fontSize {heightY * 0.014}</Text>
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  textStyle: {
    fontSize: heightY * 0.014,
  }
})

这个想法是根据屏幕的高度获取fontSize 示例计算:

// Height 785,.. -> fontSize = 11 
// Height 1000 -> fontSize = 14
// Height 1285,.. -> fontSize = 18

如果您希望它取决于您的屏幕宽度,您也可以尝试使用它:

var widthX = Dimensions.get("window").width;

需要用这种方式我用过这个,效果很好。

react-native-responsive-screen npm install react-native-responsive-screen --save

就像我有一个设备 1080x1920

The vertical number we calculate from height **hp**
height:200
200/1920*100 = 10.41% - height:hp("10.41%")


The Horizontal number we calculate from width **wp**
width:200
200/1080*100 = 18.51% - Width:wp("18.51%")

它适用于所有设备

一种稍微不同的方法对我有用:-

const normalize = (size: number): number => {
  const scale = screenWidth / 320;
  const newSize = size * scale;
  let calculatedSize = Math.round(PixelRatio.roundToNearestPixel(newSize))

  if (PixelRatio.get() < 3)
    return calculatedSize - 0.5
  return calculatedSize
};

请参考Pixel Ratio ,因为这可以让您更好地根据设备密度设置功能。

你可以使用这样的东西。

var {height, width} = Dimensions.get('window'); var textFontSize = 宽度 * 0.03;

inputText: {
    color : TEXT_COLOR_PRIMARY,
    width: '80%',
    fontSize: textFontSize
}

希望这有助于不安装任何第三方库。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM