简体   繁体   English

UIImageView约束是1:1长宽比和1:1缩放到原始比例吗?

[英]UIImageView constraint to be 1:1 aspect ratio and 1:1 scaled to original?

Is there any simple way to achieve a 1:1 aspect ratio and scale to the original image inside an ImageView ? 是否有任何简单的方法可以实现1:1的纵横比并缩放到ImageView中的原始图像?

I don't want only to keep the Image aspect ratio, I want it to be exactly the same size as the underlying image (1:1 scale also to original)... not smaller, not bigger... so it will be 1:1 on screen in therms of pixels or UIKit points or w/e with the original (scaling 1). 我不仅要保持图像的长宽比,还希望它与基础图像的尺寸完全相同(也与原始图像比例为1:1)...不小于,不大于...所以它将是在屏幕上以像素为单位或UIKit点的热或与原始图像的比例为1:1(缩放1)。

If you only set aspect ratio, the image might scale up or down, whilst keeping aspect ratio. 如果仅设置纵横比,则图像可能会放大或缩小,同时保持纵横比。 I want to prevent this behaviour and to tell it not to scale. 我想防止这种行为,并告诉它不要扩大规模。

How can I set the scale to be 1 as a constraint ? 如何将小数位数设置为1作为约束? Is there any way in doing this, without any hardcoding on width / height constraints to match the size of the original image ? 有没有办法做到这一点,而没有对宽度/高度限制进行任何硬编码以匹配原始图像的大小?

Basically I want to tell the autolayout... here is the image, don't touch it, never scale it no matter what, let it be exactly as the original (scaling 1). 基本上,我想告诉自动布局...这是图像,不要触摸它,无论如何都不要缩放它,使其与原始图像完全一样(缩放1)。

UPDATE: 更新:

The only way I could achieve this is by setting the hugging / compression priorities to higher than other items in the layout. 我可以实现此目的的唯一方法是将拥抱/压缩优先级设置为高于布局中的其他项目。 Only setting aspect ratio constraint doesn't do it... I think there is no other way to ensure this behaviour without touching compression / hugging priorities. 仅设置宽高比约束是行不通的...我认为没有其他方法可以确保这种行为而无需触及压缩/拥抱优先级。

Set the contentMode to aspectFit . contentMode设置为aspectFit

See Apple official documentation : 请参阅Apple官方文档

The option to scale the content to fit the size of the view by maintaining the aspect ratio. 通过保持纵横比来缩放内容以适合视图大小的选项。 Any remaining area of the view's bounds is transparent. 视图边界的所有剩余区域都是透明的。

Don't put any height or aspect ratio constraint to your UIImageView just put the width constraint or leading and trailing constraint whatever suits your need. 不要在您的UIImageView放置任何高度或宽高比约束,而只是将宽度约束或前导和尾随约束放入任何适合您的需求。 And make contentMode AspectFill . 并使contentMode AspectFill

ImageView will scale automatically to match the aspect ratio of the image it holds. ImageView将自动缩放以匹配其所持图像的纵横比。 However make sure to have a height <= the maximum height you should have(In the images below I should put height <= the screen height) so that the image doesn't go beyond the desired bounds. 但是请确保高度<=您应该具有的最大高度(在下面的图像中,我应该将height <=屏幕高度),以使图像不会超出期望的范围。

在此处输入图片说明 在此处输入图片说明

Try setting the ContentMode of your ImageView as Center . 尝试将ImageView的ContentMode设置为Center

Also remember to set clip to bounds. 还记得将剪辑设置为边界。

imageView.clipsToBounds = true
imageView.contentMode = .center

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

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