Created
December 10, 2025 00:41
-
-
Save Mif2006/f7126e68446beb15765c8fbd6b29f395 to your computer and use it in GitHub Desktop.
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
| import { Dimensions, Platform, PixelRatio } from 'react-native'; | |
| import * as Device from 'expo-device'; | |
| interface DeviceSpec { | |
| model: string; | |
| widthMM: number; | |
| screenWidthDP: number; | |
| } | |
| // Your original catalog — unchanged | |
| const DEVICE_CATALOG: DeviceSpec[] = [ | |
| // (your full list exactly as provided) | |
| // --- iPhone models --- | |
| { model: 'iPhone 15 Pro Max', widthMM: 76.7, screenWidthDP: 430 }, | |
| { model: 'iPhone 15 Pro', widthMM: 70.6, screenWidthDP: 393 }, | |
| // ... rest of your catalog ... | |
| ]; | |
| const FALLBACK_DEVICE: DeviceSpec = { | |
| model: 'Fallback', | |
| widthMM: 71.5, // e.g., iPhone 13 | |
| screenWidthDP: 390, | |
| }; | |
| function findDeviceSpec(): { spec: DeviceSpec; isFallback: boolean } { | |
| const runtimeModel = (Device.modelName || '').trim(); | |
| if (!runtimeModel) { | |
| return { spec: FALLBACK_DEVICE, isFallback: true }; | |
| } | |
| const cleanRuntime = runtimeModel.toLowerCase(); | |
| for (const spec of DEVICE_CATALOG) { | |
| const catalogModel = spec.model.toLowerCase(); | |
| if (cleanRuntime.includes(catalogModel) || catalogModel.includes(cleanRuntime)) { | |
| return { spec, isFallback: false }; | |
| } | |
| } | |
| return { spec: FALLBACK_DEVICE, isFallback: true }; | |
| } | |
| // NEW: Apply empirical calibration only to fallback | |
| const FALLBACK_MM_OFFSET = 1.0; // +1 mm to correct consistent error | |
| export function mmToPx(mm: number): number { | |
| if (Platform.OS === 'web') { | |
| return (mm / 25.4) * 96; | |
| } | |
| const { spec, isFallback } = findDeviceSpec(); | |
| let adjustedMM = mm; | |
| if (isFallback) { | |
| adjustedMM += FALLBACK_MM_OFFSET; // compensate for known –1mm bias | |
| } | |
| const percentageOfWidth = adjustedMM / spec.widthMM; | |
| return percentageOfWidth * spec.screenWidthDP; | |
| } | |
| export function pxToMM(px: number): number { | |
| if (Platform.OS === 'web') { | |
| return (px * 25.4) / 96; | |
| } | |
| const { spec, isFallback } = findDeviceSpec(); | |
| const percentageOfScreen = px / spec.screenWidthDP; | |
| let mm = percentageOfScreen * spec.widthMM; | |
| if (isFallback) { | |
| mm -= FALLBACK_MM_OFFSET; // reverse the offset | |
| } | |
| return mm; | |
| } | |
| export function getPhysicalScreenWidth(): number { | |
| const { spec, isFallback } = findDeviceSpec(); | |
| let width = spec.widthMM; | |
| if (isFallback) { | |
| width += FALLBACK_MM_OFFSET; | |
| } | |
| return width; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment