Last active
June 2, 2022 19:04
-
-
Save dnedrow/3183498af6425475f5ed8f84239b3ea9 to your computer and use it in GitHub Desktop.
React Native routines for calculating percent of screen size in device independent pixels
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Functions found at: https://medium.com/building-with-react-native/how-to-develop-responsive-uis-with-react-native-1x03-a448097c9503 | |
| import ExtraDimensions from 'react-native-extra-dimensions-android'; | |
| import DeviceInfo from 'react-native-device-info'; | |
| import {Dimensions, PixelRatio, Platform} from "react-native"; | |
| export const windowHeight = | |
| Platform.OS === 'ios' ? Dimensions.get('window').height : ExtraDimensions.get('REAL_WINDOW_HEIGHT'); | |
| export const windowWidth = | |
| Platform.OS === 'ios' ? Dimensions.get('window').width : ExtraDimensions.get('REAL_WINDOW_WIDTH'); | |
| /** | |
| * Returns a width derived from the given percentage and the actual screen width. | |
| * @example | |
| * const Tile = styled.View` | |
| * width: ${widthPercentageToDP('98%')}; | |
| * . | |
| * . | |
| * . | |
| * `; | |
| * @param widthPercent | |
| */ | |
| export const widthPercentageToDP = (widthPercent: string) => { | |
| const screenWidth = windowWidth; | |
| // Convert string input to decimal number | |
| const elemWidth = parseFloat(widthPercent); | |
| return PixelRatio.roundToNearestPixel(screenWidth * elemWidth / 100); | |
| }; | |
| /** | |
| * Returns a height derived from the given percentage and the actual screen height. | |
| * @example | |
| * const Tile = styled.View` | |
| * height: ${heightPercentageToDP('98%')}; | |
| * . | |
| * . | |
| * . | |
| * `; | |
| * @param heightPercent | |
| */ | |
| export const heightPercentageToDP = (heightPercent: string) => { | |
| const screenHeight = windowHeight; | |
| // Convert string input to decimal number | |
| const elemHeight = parseFloat(heightPercent); | |
| return PixelRatio.roundToNearestPixel(screenHeight * elemHeight / 100); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment