如何使用固定宽度和自动布局正确缩放图像?

时间:2013-12-13 21:23:59

标签: ios objective-c uiimageview

我有一个动态UIImage和UIImageView,固定宽度为280.0px,我正在使用自动布局。在UIImage视图中,我设置了宽度和高度约束,并降低了高度约束的优先级。我选择了“纵横比较”,并将内容拥抱和压缩优先级提高到1000。 在这种情况下,UIImageView会调整大小以保持比例,但高度比我想要的要大。保留宽高比,因为UIImageView的顶部和底部有空白空间。我想删除这些空格并自动调整高度以完全适合UIImage。

2 个答案:

答案 0 :(得分:7)

像这样......

UIImage *image = ...;
UIImageView *imageView = ...;

imageView.image = image;
float ar = image.size.width/image.size.height;

NSLayoutConstraint* aspectConstraint = [NSLayoutConstraint constraintWithItem: imageView
                                                         attribute: NSLayoutAttributeWidth
                                                         relatedBy: NSLayoutRelationEqual
                                                            toItem: imageView
                                                         attribute: NSLayoutAttributeHeight
                                                        multiplier: ar
                                                          constant: 0];

[parentView addConstraint: aspectConstraint];

答案 1 :(得分:1)

我已经解决了如下:

-(CGFloat) scaleImageAutoLayout:(UIImageView *)imageView withWidth:(CGFloat)width
{
    CGFloat scale = width/imageView.image.size.width;
    CGFloat height = imageView.image.size.height * scale;
    NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(imageView);
    [imageView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString     stringWithFormat:@"V:[imageView(%f)]",ceilf(height)]
                                                                  options:0 metrics:nil    views:viewsDictionary]];
    return height;
}