简体   繁体   English

渲染前计算屏幕尺寸的图像尺寸

[英]Calculate image dimensions on screen size before rendering

Is there a way of calculating / estimating what the image size would be depending on the screen resolution before the image has been rendered? 有没有一种方法可以计算/估计在渲染图像之前取决于屏幕分辨率的图像大小? I need more logical help rather than code to be honest. 老实说,我需要更多的逻辑帮助,而不是代码。 What do I need to calculate? 我需要计算什么?

Image size: 800px * 450px 图片尺寸:800px * 450px

Window size: 424px * 728px 视窗大小:424px * 728px

The image works out to be 424px * 239px. 图片的大小为424px * 239px。 I need to calculate this in code so I can adjust positions of other elements following after (absolute / fixed elements). 我需要在代码中进行计算,以便可以在之后(绝对/固定元素)调整其他元素的位置。

What I have done so far is; 到目前为止,我所做的是;

var ratio1 = (this.retrievedNewsArticle.featuredImage.width / this.retrievedNewsArticle.featuredImage.height);
var ratio2 = ($(window).innerWidth() / this.retrievedNewsArticle.featuredImage.width);

// Ratio 1 = 424
// Ratio 2 = 0.53

So what's next? 下一个是什么?

It sounds like you already know the image's size, and it sounds like you want the image to be the full width of the window, and just need to know how to determine the height of the image. 听起来您已经知道图像的大小,并且听起来像您希望图像成为窗口的整个宽度,并且只需要知道如何确定图像的高度即可。 If so, the target height is the image height times the windows width divided by the image width: 如果是这样,则目标高度是图像高度乘以窗口宽度除以图像宽度:

var renderedWidth = imageWidth;
var renderedHeight = imageHeight * (windowWidth / imageWidth);

That maintains the aspect ratio. 这样可以保持纵横比。

That assumes the image is always wider than the screen. 假定图像始终比屏幕宽。 Let's remove that assumption. 让我们删除该假设。

If you want the image to stretch to fill: 如果要拉伸图像以填充:

var renderedWidth, renderedHeight;
if (windowWidth >= imageWidth) {
    renderedWidth = imageWidth * (windowWidth / imageWidth);
} else {
    renderedWidth = imageWidth;
}
renderedHeight = imageHeight * (windowWidth / renderedWidth);

If you don't want the image to stretch to fill: 如果您不希望图像拉伸以填充:

var renderedWidth, renderedHeight;
if (windowWidth >= imageWidth) {
    renderedWidth = imageWidth;
    renderedHeight = imageHeight;
} else {
    renderedWidth = imageWidth;
    renderedHeight = imageHeight * (windowWidth / imageWidth);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM