Scaling UIImageView to fit width with AutoLayout

霸气de小男生 提交于 2019-12-06 00:58:48

OK, I found a suitable solution to my problem.

I calculate the correct height that I want for my picture like this :

correctedHeight = screenWidth / width * height

After that, I add a height constraint programmatically in the updateViewConstraints method.

I use this code :

[imageView addConstraint:[NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant: correctImageViewHeight]];

Two things to think of after that :

  • removing the constraint each time this method is called (otherwise you end up with conflicting constraints). To achieve this, I use [imageView removeConstraint: imageView.constraints.lastObject] ;
  • putting[super updateViewConstraints] ; inside the method. If you forget, it crashes.

I haven't done it yet, but I can easily see how I could update my correctHeight variable when the device rotates.

Use the following code

imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.autoresizingMask =   
    ( UIViewAutoresizingFlexibleBottomMargin
    | UIViewAutoresizingFlexibleHeight
    | UIViewAutoresizingFlexibleLeftMargin
    | UIViewAutoresizingFlexibleRightMargin
    | UIViewAutoresizingFlexibleTopMargin
    | UIViewAutoresizingFlexibleWidth );

Can you provide code?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!