如何从 React Native 上的 uri 获取图像高度和宽度? [英] How to get image height and width from uri on React Native?

查看:436
本文介绍了如何从 React Native 上的 uri 获取图像高度和宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我尝试使用 React Native 提供的 Image.getSize 函数.但是当我尝试在函数外使用高度和宽度时,它似乎为零.这是我的代码:

So, I tried to use function that provided by React Native which is Image.getSize. But when I try to use height and width outside the function it appears to be nil. Here is my code:

var theHeight = 0;
Image.getSize(url,(height, width)=>{
 theHeight = height;
})

console.log("test get height "+theHeight);

结果是

测试得到高度0

我做错了什么?

推荐答案

您的代码有两个问题.第一个是 Image.getSize 异步调用它的回调.您需要将依赖于图像大小的代码放在回调中.

There are two problems with your code. The first is that Image.getSize invokes its callbacks asynchronously. You need to put your code that relies on the image size within the callbacks.

第二个问题是成功回调的参数是(width, height),而不是相反.

The second problem is that the arguments to the success callback are (width, height), not the other way around.

你应该写:

Image.getSize(url, (width, height) => {
  console.log(`The image dimensions are ${width}x${height}`);
}, (error) => {
  console.error(`Couldn't get the image size: ${error.message}`);
});

这篇关于如何从 React Native 上的 uri 获取图像高度和宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆