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.
Auto layout is a property you can add to frames and components. It lets you create designs that grow to fill or shrink to fit, and reflow as their contents change. This is great when you need to add new layers, accommodate longer text strings, or maintain alignment as your designs evolve.
Auto Layout constraints allow us to create views that dynamically adjust to different size classes and positions. The constraints will make sure that your views adjust to any size changes without having to manually update frames or positions.
A vanilla UIView instance, for example, does not have an intrinsic content size. This means that you need to add four explicit constraints to describe the size and position of a UIView instance in a user interface.
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];
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With