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

Ios 如何使用固定宽度和自动布局正确缩放图像?,ios,objective-c,uiimageview,Ios,Objective C,Uiimageview,我有一个动态UIImage和一个固定宽度为280.0px的UIImageView,我使用的是自动布局。在UIImage视图上,我设置了宽度和高度约束,并降低了高度约束的优先级。我选择了“方面匹配”,并将内容拥抱和压缩优先级提高到1000。 在这种情况下,UIImageView会调整大小以保持比例,但高度比我想要的大。由于UIImageView的顶部和底部都有空白,因此保留了纵横比。我想删除这些空格,并自动调整高度,使其与UIImage完美匹配。类似的内容 UIImage *image = ...

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

类似的内容

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];

我已经解决了如下问题:

-(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;
}

谢谢你的回答是对的。我已经用这种方法解决了这个问题,但是使用约束的视觉格式这个答案是完美而简单的