UNPKG

react-native-responsiveness-tool

Version:

A utility package for scaling UI elements in React Native based on device dimensions and screen density.

62 lines (52 loc) 1.73 kB
import { Dimensions, PixelRatio } from "react-native"; // Screen dimensions const { width: DEVICE_WIDTH, height: DEVICE_HEIGHT } = Dimensions.get("window"); const DEVICE_SCALE: number = Math.sqrt(DEVICE_WIDTH * DEVICE_HEIGHT) / 100; // Reference dimensions let REFERENCE_WIDTH: number = 360; let REFERENCE_HEIGHT: number = 800; const SCALE_FACTOR: number = 0.5; // Function to set new reference dimensions const setReferenceDimensions = (width: number, height: number) => { REFERENCE_WIDTH = width; REFERENCE_HEIGHT = height; }; // Percentage-based scalers const scaleWidthPercent = (widthPercent: string) => PixelRatio.roundToNearestPixel( (DEVICE_WIDTH * parseFloat(widthPercent)) / 100 ); const scaleHeightPercent = (heightPercent: string) => PixelRatio.roundToNearestPixel( (DEVICE_HEIGHT * parseFloat(heightPercent)) / 100 ); // Image scaler by ratio const imageHeightFromWidth = (width: number, height: number) => { const ratio = height / width; return width * ratio; }; // Scalers const sw = (size: number) => PixelRatio.roundToNearestPixel(size * (DEVICE_WIDTH / REFERENCE_WIDTH)); const sh = (size: number) => PixelRatio.roundToNearestPixel(size * (DEVICE_HEIGHT / REFERENCE_HEIGHT)); const moderateScale = (size: number) => PixelRatio.roundToNearestPixel(size + (sh(size) - size)); const adaptiveScale = (size: number, factor: number = SCALE_FACTOR) => PixelRatio.roundToNearestPixel(size + (sw(size) - size) * factor); export { REFERENCE_WIDTH, REFERENCE_HEIGHT, SCALE_FACTOR, DEVICE_WIDTH, DEVICE_HEIGHT, DEVICE_SCALE, sw, sh, moderateScale, adaptiveScale, scaleWidthPercent, scaleHeightPercent, imageHeightFromWidth, setReferenceDimensions, };