首页 > 解决方案 > 如何在不同的设备上呈现相同的图片?

问题描述

我是移动开发的新手,一些非常重要的事情让我很好奇。

假设我想在屏幕的 100% 宽度和高度上呈现图片。图片应该是哪种尺寸,以便我可以在每部手机上展示它,这是最佳的?

处理这个问题的常用策略是什么?

谢谢

标签: javascriptreactjsreact-nativescreen-resolutionmobile-development

解决方案


前段时间我需要这样做,所以我写了一个组件。我在这里基本上做的是比较屏幕比例和图像比例,并使用一个简单的公式相应地设置宽度和高度。

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;

就这样,无论您的图像比例或屏幕比例是多少,图像都会适合屏幕。

但请记住,如果用户旋转屏幕,则不会再次计算,因此如果您的应用启用了纵向和横向模式,则必须在屏幕方向更改时再次进行计算。


推荐阅读