首页 > 解决方案 > 如何获取 Image 组件内显示内容的实际大小(包含模式)?

问题描述

我试图匹配一个分量上方的一些向量Image。为了做到这个像素完美,我需要知道Image组件内显示的图像的大小。

此时我有了组件布局的宽度和高度,但无法弄清楚一旦在Image组件内部如何计算图像的宽度和高度。

我试图用 with 和反之亦然的比例来计算以下方式,但在某些情况下(特别是垂直图像)这不起作用。

/*
    Calculate proportional width of displayed image:
    
    photo.width -> width
    photo.height -> x
*/
var x = (width * photo.height) / photo.width;
/*
    calculate proportional height of displayed image:
    
    photo.height -> height
    photo.width -> y
*/
var y = (height * photo.width) / photo.height;

标签: imagereact-native

解决方案


使用图像元素的.clientWidth.clientHeight属性来确定其实际缩放的宽度和高度。如果由于某种原因这不是一个选项,您可以自己进行计算:

如果 ( photo.width/ photo.height) > ( containerWidth/ containerHeight) 则照片的纵横比比容器宽,并且可以缩放以适应容器的全宽,并带有信箱(上下空白)。照片的新宽度和高度为:

newPhotoWidth = containerWidth
newPhotoHeight = containerWidth * ( photo.height / photo.width )

例如,如果容器为 500x400,照片为 300x50:

newPhotoWidth = 500
newPhotoHeight = 83.33 // i.e. 500 * ( 50 / 300 )

如果 ( photo.width/ photo.height) > ( containerWidth/ containerHeight) 则照片的纵横比比容器窄,并且可以缩放以适应容器的全高,左右两侧带有信箱(如示例图像所示)。照片的新宽度和高度为:

newPhotoWidth = containerHeight * ( photo.width / photo.height )
newPhotoHeight = containerHeight

例如,如果容器为 500x400,照片为 50x300:

newPhotoHeight = 66.66  // i.e. 400 * ( 50 / 300 )
newPhotoWidth = 400

推荐阅读