简体   繁体   中英

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 ?

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).

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 ? 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).

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 .

See Apple official documentation :

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. And make contentMode AspectFill .

ImageView will scale automatically to match the aspect ratio of the image it holds. 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.

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

Try setting the ContentMode of your ImageView as Center .

Also remember to set clip to bounds.

imageView.clipsToBounds = true
imageView.contentMode = .center

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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