image - 如何获取 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;
解决方案
使用图像元素的.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
推荐阅读
- trace - 在 istio 中覆盖 x-request-id 标头
- django - 使用没有“决策者”模型字段的 FactoryBoy 的 Maybe 声明
- spring-boot - OAuth2配置了部署在Google AppEngine中的SpringBoot应用程序不重定向到google登录,但在本地工作正常
- python-3.x - 本体填充
- linux - 脚本中的 LDAP 搜索导致“DNS SRV:内存不足”
- ios - 标签文本为大字符串时,ScrollView 不滚动
- graphql - 在 GraphQL 模式上应用 DRY 原则
- android - 获取数据类的所有字段的值时出错
- r - r 传单图标支持的颜色
- ios - 班级的大小是否会影响完成排序所需的时间?