javascript - 如何在不同的设备上呈现相同的图片?
问题描述
我是移动开发的新手,一些非常重要的事情让我很好奇。
假设我想在屏幕的 100% 宽度和高度上呈现图片。图片应该是哪种尺寸,以便我可以在每部手机上展示它,这是最佳的?
处理这个问题的常用策略是什么?
谢谢
解决方案
前段时间我需要这样做,所以我写了一个组件。我在这里基本上做的是比较屏幕比例和图像比例,并使用一个简单的公式相应地设置宽度和高度。
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;
就这样,无论您的图像比例或屏幕比例是多少,图像都会适合屏幕。
但请记住,如果用户旋转屏幕,则不会再次计算,因此如果您的应用启用了纵向和横向模式,则必须在屏幕方向更改时再次进行计算。
推荐阅读
- java - 使用 @KafkaListener 注释的方法不会传播遇到的异常。由于这个原因,无法调用我的重试配置
- node.js - 导入 var firebaseui = require('firebaseui'); 错误窗口未定义
- c# - 如何在 C# 中向服务器发送文件和字符串?
- matlab - 如何在 MATLAB 中使用三次方程求解器求解/优化 9 个非线性方程?
- proxy - 在单个域上部署多个存储库(通过 Netlify 中的代理)
- javascript - 使用 ng-repeat 制作一个列表,由“自定义类别”(AngularJS)分隔
- python-3.x - 从熊猫数据框中选择具有两个级别(二元变量)的列
- javascript - 使用 Axios 发布请求的 JWT 授权
- c# - 具有不同变量的相同功能
- php - php - 比较和打印数组中的相同值