Skip to content

Instantly share code, notes, and snippets.

@jrapala
Last active July 6, 2023 12:26
Show Gist options
  • Save jrapala/27ffaa31437e8517e956e1521821fcc3 to your computer and use it in GitHub Desktop.
Save jrapala/27ffaa31437e8517e956e1521821fcc3 to your computer and use it in GitHub Desktop.
Normalize React Native font sizes
// How to use:
//
// StyleSheet or inline styles:
// fontSize: normalize(15),
//
// styled-components:
// font-size: ${normalize(15) + "px"};
import { Dimensions, Platform, PixelRatio } from "react-native"
const { width: SCREEN_WIDTH } = Dimensions.get("window")
// Based on iPhone 5s's scale
const scale = SCREEN_WIDTH / 320
const checkIfTablet = (): boolean => {
const pixelDensity = PixelRatio.get()
const adjustedWidth = SCREEN_WIDTH * pixelDensity
const adjustedHeight = SCREEN_WIDTH * pixelDensity
if (pixelDensity < 2 && (adjustedWidth >= 1000 || adjustedHeight >= 1000)) {
return true
} else {
return (
pixelDensity === 2 &&
(adjustedWidth >= 1920 || adjustedHeight >= 1920)
)
}
}
export default function normalize(size: number): number {
const isTablet = checkIfTablet()
// NOTE: Tablet scaling hasn't been fully tested.
const newSize = isTablet ? (size * scale) / 2 : size * scale
if (Platform.OS === "ios") {
return Math.round(PixelRatio.roundToNearestPixel(newSize))
} else {
return Math.round(PixelRatio.roundToNearestPixel(newSize)) - 2
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment