Skip to content

Instantly share code, notes, and snippets.

@ridvanaltun
Last active November 23, 2023 14:44
Show Gist options
  • Save ridvanaltun/433b4a555e465815edbab9d2c99ff426 to your computer and use it in GitHub Desktop.
Save ridvanaltun/433b4a555e465815edbab9d2c99ff426 to your computer and use it in GitHub Desktop.

Revisions

  1. ridvanaltun revised this gist Nov 23, 2023. No changes.
  2. ridvanaltun created this gist Nov 23, 2023.
    95 changes: 95 additions & 0 deletions styling.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,95 @@
    import {Dimensions, PixelRatio, StyleSheet} from 'react-native';

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

    const PROPERTIES_DEPENDING_ON_WIDTH = [
    'width',
    'marginLeft',
    'marginRight',
    'marginHorizontal',
    'paddingLeft',
    'paddingRight',
    'paddingHorizontal',
    'borderLeftWidth',
    'borderRightWidth',
    'left',
    'right',
    'minWidth',
    'maxWidth',
    ];

    const PROPERTIES_DEPENDING_ON_HEIGHT = [
    'height',
    'marginTop',
    'marginBottom',
    'marginVertical',
    'paddingTop',
    'paddingBottom',
    'paddingVertical',
    'borderTopWidth',
    'borderBottomWidth',
    'top',
    'bottom',
    'minHeight',
    'maxHeight',
    'lineHeight',
    ];

    const PROPERTIES_DEPENDING_ON_NEITHER = [
    'fontSize',
    'margin',
    'padding',
    'borderWidth',
    'borderRadius',
    'borderTopLeftRadius',
    'borderTopRightRadius',
    'borderBottomLeftRadius',
    'borderBottomRightRadius',
    ];

    const BASE_WIDTH = 375; // based on iPhone 6-8 width
    const BASE_HEIGHT = 667; // based on iPhone 6-8 height

    class StylingHelper {
    static setGuidelineBaseDimensions(
    guidelineBaseWidth = BASE_WIDTH,
    guidelineBaseHeight = BASE_HEIGHT,
    ) {
    const scalingFactor = 1;
    const horizontalFactor = (width / guidelineBaseWidth) * scalingFactor;
    const verticalFactor = (height / guidelineBaseHeight) * scalingFactor;
    const adimensionalFactor = (horizontalFactor + verticalFactor) / 2;

    PROPERTIES_DEPENDING_ON_WIDTH.forEach(key => {
    StyleSheet.setStyleAttributePreprocessor(key, value => {
    if (typeof value === 'number') {
    return PixelRatio.roundToNearestPixel(value * horizontalFactor);
    }

    return value;
    });
    });

    PROPERTIES_DEPENDING_ON_HEIGHT.forEach(key => {
    StyleSheet.setStyleAttributePreprocessor(key, value => {
    if (typeof value === 'number') {
    return PixelRatio.roundToNearestPixel(value * verticalFactor);
    }

    return value;
    });
    });

    PROPERTIES_DEPENDING_ON_NEITHER.forEach(key => {
    StyleSheet.setStyleAttributePreprocessor(key, value => {
    if (typeof value === 'number') {
    return PixelRatio.roundToNearestPixel(value * adimensionalFactor);
    }

    return value;
    });
    });
    }
    }

    export default StylingHelper;