How do i scale an image correctly with fixed width and auto layout?

跟風遠走 提交于 2019-12-10 03:38:30

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/20576251/how-do-i-scale-an-image-correctly-with-fixed-width-and-auto-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!