i've a dynamic UIImage and a UIImageView with fixed width of 280.0px and i'm using auto layout. On the UIImage view I've set width and height constraints and lowered the priority of the height constraint. I've selected "aspect fit", and raised content hugging and compression priority to 1000. In that case the UIImageView is resized to maintain the ratio, but the height is bigger then i want. The aspect ratio is preserved because there are empty spaces on top and bottom of the UIImageView. I would like to remove these spaces and automatically resize the height to perfectly fitting the UIImage.
7
votes
2 Answers
7
votes
Something like this...
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
votes
I've solved as follows:
-(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;
}