React-Native Image rendering on different android devices based on their DPI

418 Views Asked by At

I am new to react-native and trying to render images on different android device based on the DPI. Need Help with it.

Code for getting DPI of device is -

import {PixelRatio} from 'react-native';

const PDI = PixelRatio.get();
var localPath='';

if(PDI == 1){
    localPath = '../../assets/img/drawable-mdpi'
}
else if(PDI == 1.5){
    localPath = '../../assets/img/drawable-hdpi'
}
else if(PDI == 2){
    localPath = '../../assets/img/drawable-xhdpi'
}
else if(PDI == 3){
    localPath = '../../assets/img/drawable-xxhdpi'
}
else if(PDI == 3.5){
    localPath = '../../assets/img/drawable-xxxhdpi'
}
export {PDI, localPath};

And the react-native app.js file is -

import React, {Component} from 'react';
import {View, Image, StyleSheet, StatusBar, Alert} from 'react-native';
import { PDI, localPath } from '../../helper/device-size-android/GetDeviceSizeAndroid';

export default class TestImg extends Component {
  componentDidMount() {
    setTimeout(() => {
      this.props.navigation.navigate('Home')
    }, 3000);
  }
  render() {
    return (
      <View>
         <StatusBar
            barStyle = "dark-content"
         />
        <Image
          source={require(localPath + '/Splash.png')}
        />
      </View>
    );
  }
}
1

There are 1 best solutions below

0
On

Your sequence of if statements isn't going to work if PixelRatio.get() doesn't return one of the five values you single out, which are just typical values mentioned in the documentation that don't necessarily match the resolution of a particular phone. Compare PixelRatio.get() to intervals for robustness:

if(dpi<1.2){
  localPath = '../../assets/img/drawable-mdpi'
}else if(dpi<1.7){
  localPath = '../../assets/img/drawable-hdpi'
}else if(dpi<2.6){
  localPath = '../../assets/img/drawable-xhdpi'
}else if(dpi<3.2){
  localPath = '../../assets/img/drawable-xxhdpi'
}else {
  localPath = '../../assets/img/drawable-xxxhdpi'
}

Better yet, let the React Native Image component do the work with multiple images specified in the source property.