How to present the same picture over different devices?

Viewed 120

I'm new to mobile development and something really crucial got me curious.

Suppose I want to present a picture on 100% width and height of the screen. Which size should the picture be so I could present it on every mobile phone, optimally?

What are the common strategies to deal with this problem?

Thanks

2 Answers

I needed to do that some time ago, so I wrote a component. What I'm basically doing here is comparing the screen ratio with the image ratio, and setting the width and height accordingly using a simple formula.

const Photo = ({imageUri}) => {
    const [imageSize, setImageSize] = useState({width: 0, height: 0});

    useEffect(() => {
        Image.getSize(imageUri, (imageWidth, imageHeight) => {
            const screenWidth = Dimensions.get('window').width;
            const screenHeight = Dimensions.get('window').height;

            if (imageWidth / imageHeight < screenWidth / screenHeight) {
                setImageSize({
                    width: imageWidth + (imageWidth * (screenHeight - imageHeight)) / imageHeight,
                    height: screenHeight,
                });
            } else {
                setImageSize({
                    height: imageHeight + (imageHeight * (screenWidth - imageWidth)) / imageWidth,
                    width: screenWidth,
                });
            }
        });
    }, []);

    return (
        <View style={styles.container}>
            <Image style={imageSize} source={{uri: imageUri}} />
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: 'black',
    },
});

export default Photo;

And there you go, no matter what your image ratio or screen ratio is, the image will fit in the screen.

All though keep in mind that if the user rotates the screen, this will not be calculated again, so if you have an app that has portrait and landscape mode enabled, you have to do the calculation again on screen orientation change.

You can get the dimensions of that particular screen, and use that entire screen width and screen height supplied to your picture.

import { Dimensions } from 'react-native';

const SCREEN_HEIGHT = Dimensions.get('window').height;
const SCREEN_WIDTH = Dimensions.get('window').width;

now you can pass these values.

<Image uri={myUri} style={{ width: SCREEN_WIDTH, height: SCREEN_HEIGHT }}
Related