繁体   English   中英

UIImageView具有自动布局和最大尺寸保持纵横比

[英]UIImageView with auto-layout and max size keeping aspect ratio

我有一个在源代码中生成的UIImageView (以编程方式)。 UIImageView需要具有宽度和高度的最大尺寸。 在此视图中,我从URL加载图像并在下载结束后设置。 我以前不知道,图像的大小是多少,但我需要保持宽高比并使UIImageView具有维持该方面的大小。

如果图像较小,在一个或两个维度上,我希望UIImageView具有保持纵横比而不拉伸图像所需的大小。

我将给出两个例子,考虑UIImageView的最大尺寸为250 X 350

例1:

图像尺寸为800 X 800 UIImageView的大小需要为250 X 250

例2:

图像尺寸为200 X 250 UIImageView的大小需要为200 X 250

如何使用自动布局执行此操作。

这里你需要三个约束。 一个保持纵横比,一个确保宽度不大于最大值,一个确保高度不大于最大值。 截至2016年8月,Interface Builder不支持引用其他约束的约束,因此 - 至少 - 宽高比约束必须在代码中完成。

宽高比是唯一可以考虑的因素。 设V_w和V_h分别为图像视图的宽度和高度。 设I_w和I_h分别是图像的宽度和高度。 然后,为了保持图像的纵横比,必须保持以下等式:

V_w / V_h = I_w / I_h

或者,等效地:

V_w =(I_w / I_h)* V_h

好的,看起来不错。 我们来写一些代码。 在此代码中,我假设您之前定义了MAX_HEIGHTMAX_WIDTH 请注意 ,此代码必须以iOS 9.0或更高版本为目标。 如果您的目标是早期版本的iOS,请参阅下面的块。

// Constrain the desired aspect ratio
[imageView.widthAnchor constraintEqualToAnchor:imageView.heightAnchor
                                    multiplier:aspectRatioMult].active = YES;

// Constrain height
[imageView.heightAnchor constraintLessThanOrEqualToConstant:MAX_HEIGHT].active = YES;

// Constrain width
[imageView.widthAnchor constraintLessThanOrEqualToConstant:MAX_WIDTH].active = YES;

对于在9.0之前定位iOS版本的代码, NSLayoutAnchor不可用。 相反,你必须使用NSLayoutConstraint

CGFloat aspectRatioMult = (imageView.image.size.width / imageView.image.size.height);

// Constrain the desired aspect ratio
[imageView addConstraint:
  [NSLayoutConstraint constraintWithItem:imageView
                               attribute:NSLayoutAttributeWidth
                               relatedBy:NSLayoutRelationEqual
                                  toItem:imageView
                               attribute:NSLayoutAttributeHeight
                              multiplier:aspectRatioMult
                                constant:0]];

// Constrain height
[imageView addConstraints:
  [NSLayoutConstraint constraintsWithVisualFormat:@"V:[imageView(<=max)]"
                                          options:0
                                          metrics:@{@"max" : @(MAX_HEIGHT)}
                                            views:@{@"imageView" : imageView}]];

// Constrain width
[imageView addConstraints:
  [NSLayoutConstraint constraintsWithVisualFormat:@"H:[imageView(<=max)]"
                                          options:0
                                          metrics:@{@"max" : @(MAX_WIDTH)}
                                            views:@{@"imageView" : imageView}]];

暂无
暂无

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

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