네이티브 응답 글꼴 크기 반응
원어민 대응 폰트는 어떻게 반응하는지 묻고 싶습니다.예를 들어 iphone 4s에서는 i Have font Size: 14, iphone 6에서는 font Size: 18 입니다.
Pixel Ratio를 사용할 수 있습니다.
예를 들어 다음과 같습니다.
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),
},
};
NAT은 다음과 같이 작성한 단순하고 간단한 확장 유틸리티 함수를 사용합니다.
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};
많은 if를 실행하는 시간을 절약할 수 있습니다.자세한 내용은 제 블로그 투고를 참조해 주세요.
Edit: I thought it might be helpful to extract these functions to their own npm package, I also included
ScaledSheet
in the package, which is an automatically scaled version of
StyleSheet
. You can find it here:
반응성 크기 중개의.
adjustsFontSizeToFit
그리고.numberOfLines
잘 먹히네요.그들은 긴 이메일을 한 줄로 조정합니다.
<View>
<Text
numberOfLines={1}
adjustsFontSizeToFit
style={{textAlign:'center',fontSize:30}}
>
{this.props.email}
</Text>
</View>
응답 유닛은 현재 리액트 네이티브에서는 사용할 수 없기 때문에 화면 크기를 검출하고 그것을 사용하여 디바이스 유형을 추론하여 폰트 크기를 조건부로 설정하는 것이 가장 좋다고 생각합니다.
다음과 같은 모듈을 작성할 수 있습니다.
function fontSizer (screenWidth) {
if(screenWidth > 400){
return 18;
}else if(screenWidth > 250){
return 14;
}else {
return 12;
}
}
각 디바이스의 기본 폭과 높이를 조회하기만 하면 됩니다.장치의 방향을 변경할 때 폭과 높이가 뒤집힌 경우 가로 세로 비율을 대신 사용하거나 두 치수 중 작은 치수를 사용하여 폭을 계산할 수 있습니다.
이 모듈 또는 이 모듈을 통해 디바이스 치수 또는 디바이스 유형을 찾을 수 있습니다.
나는 다음과 같은 방법으로 이것을 극복했다.
현재 보기에서 원하는 글꼴 크기를 선택합니다(시뮬레이터에서 사용 중인 현재 장치에 적합한지 확인하십시오).
import { Dimensions } from 'react-native'
컴포넌트 바깥쪽의 폭을 다음과 같이 정의합니다.let width = Dimensions.get('window').width;
이제 console.log(width)를 입력하고 적어둡니다.예를 들어 글꼴 크기가 15이고 너비가 360인 경우 360을 15(= 24)로 나눕니다.이것은 다양한 크기에 맞게 조정되는 중요한 값이 될 것입니다.
스타일 오브젝트에 다음과 같이 이 숫자를 사용합니다.
textFontSize: { fontSize = width / 24 },...
응답성이 뛰어난 폰트 사이즈를 갖게 되었습니다.
제가 쓴 도서관을 보세요.https://github.com/tachyons-css/react-native-style-tachyons
root-fontSize 를 지정할 수 있습니다( ).rem
)는, 기동시에, 유저에게 의존할 수 있습니다.PixelRatio
또는 기타 디바이스 특성.
그 후, 자신의 스타일과 비교한 스타일을 얻을 수 있습니다.rem
, font Size 뿐만 아니라 패딩 등:
<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}
플렉시블 레이아웃을 사용하여 응답성 있는 글꼴 크기를 위해 adjustsFontSizeToFit={true}를 사용할 수 있습니다.그리고 텍스트는 용기의 크기에 따라 조정될 것입니다.
<Text
adjustsFontSizeToFit
style={styles.valueField}>{value}
</Text>
그러나 글꼴 크기를 입력해야 하는 스타일에서는 Font Size To Fit이 조정됩니다.
valueField: {
flex: 3,
fontSize: 48,
marginBottom: 5,
color: '#00A398',
},
""를 하지 않는가 있습니다.PixelRatio.getPixelSizeForLayoutSize(/* size in dp */);
, , , , , , , 같은 입니다.pd
Android ★★★
저는 보통 이것을 사용하고 있습니다.
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;
최근 이 문제에 부딪혀 리액션 네이티브 확장 스타일시트를 사용하게 되었습니다.
할 수 있습니다.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
});
이 방법을 사용해야 할 필요가 있습니다.이것을 사용했는데, 정상적으로 동작하고 있습니다.
반응 반응 스크린 npm install react-display-response-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
};
「픽셀 비율」을 참조하면, 디바이스의 밀도에 근거해 기능을 보다 효율적으로 설정할 수 있습니다.
이런 거 써도 돼요.
var {height, width} = Dimensions.get('창'), var textFontSize = width * 0.03;
inputText: {
color : TEXT_COLOR_PRIMARY,
width: '80%',
fontSize: textFontSize
}
서드파티 라이브러리를 설치하지 않아도 도움이 되기를 바랍니다.
언급URL : https://stackoverflow.com/questions/33628677/react-native-responsive-font-size
'programing' 카테고리의 다른 글
React.js - 속성 객체를 하위 구성요소로 전달하는 방법 (0) | 2023.03.18 |
---|---|
속성 탐색기처럼 작동하는 GUI 기반 또는 웹 기반 JSON 편집기 (0) | 2023.03.18 |
MongoDB에서 $in 쿼리에 전달되는 파라미터의 최대 수는 몇 개입니까? (0) | 2023.03.13 |
ng-hide/ng-show에서 복잡한 표현이 가능합니까? (0) | 2023.03.13 |
Wordpress 사이트가 해킹됨 - 다른 사이트로 리디렉션 (0) | 2023.03.13 |