Skip to content

Instantly share code, notes, and snippets.

@richardgill
Created December 2, 2016 16:31
Show Gist options
  • Save richardgill/b8fbddda2b10261bbb0db2f0cb7090bb to your computer and use it in GitHub Desktop.
Save richardgill/b8fbddda2b10261bbb0db2f0cb7090bb to your computer and use it in GitHub Desktop.
Makes React Native components look more consistent on different device sizes. The base size is an iPhone 6.
import _ from 'lodash'
import { Dimensions, PixelRatio } from 'react-native'
import { platformIsIos } from 'expresso-common/common/platform'
const { height } = Dimensions.get('window')
const iphone6Height = 667
const pixelRatio = PixelRatio.get()
const fieldsToNormalize = [
'fontSize',
'lineHeight',
'letterSpacing',
'width',
'height',
'margin',
'marginTop',
'marginBottom',
'marginLeft',
'marginRight',
'padding',
'paddingTop',
'paddingBottom',
'paddingLeft',
'paddingRight',
]
const normalizeFontIos = (size) => {
return size
}
export const normalizeFont = (size) => {
if (platformIsIos()) {
return normalizeFontIos(size)
}
if (pixelRatio === 2) {
return Math.round(size * 1)
}
return size * 1
}
export const normalizeValue = (value) => {
return Math.round((height / iphone6Height) * value)
}
export const normalizeKeyValue = (styleKey, value) => {
if (['fontSize', 'lineHeight', 'letterSpacing'].includes(styleKey)) {
return normalizeFont(value)
}
return Math.round((height / iphone6Height) * value)
}
export const denormalizeValue = (value) => {
return Math.round((iphone6Height / height) * value)
}
export function normalizeStyle(style) {
const normalizedStyle = _.mapValues(_.pick(style, fieldsToNormalize), (value, key) => normalizeKeyValue(key, value))
return {
..._.omit(style, fieldsToNormalize),
...normalizedStyle
}
}
export default function normalizeStyles(styles) {
return _.mapValues(styles, (style) => normalizeStyle(style))
}
@henrikra
Copy link

Can you explain the things you are doing in normalizeFont function? For me for example it does not make sense to size * 1 :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment