React Native - 如何从设备存储获取图像大小(宽度和高度)?

Mal*_*ser 3 react-native

我有一个基于 Expo 的 React Native 项目。我需要在屏幕上查看图像,其样式基于该图像的宽度和高度。我怎样才能得到该图像的宽度和高度?

假设图像 uri 是file:///storage/emulated/0/WhatsApp/Media/WhatsApp%20Images/IMG-20200117-WA0019.jpg

带有代码示例的解决方案受到高度赞赏。

SDu*_*han 10

React Native Image 提供getSize()来获取远程图像的大小。

Image.getSize('uri', (width, height) => {
  this.setState({ width, height });
});
Run Code Online (Sandbox Code Playgroud)

对于本地图像,您可以使用resolveAssetSource()

Image.resolveAssetSource(source).width
Image.resolveAssetSource(source).height
Run Code Online (Sandbox Code Playgroud)

希望这对您有帮助。如有疑问,请放心。

  • 尝试将本地图像加载为``Image.resolveAssetSource(require('path')).width``` (2认同)