如何使用固定宽度和自动布局正确缩放图像? [英] How do i scale an image correctly with fixed width and auto layout?

查看:101
本文介绍了如何使用固定宽度和自动布局正确缩放图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

我已经解决了如下问题:

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

这篇关于如何使用固定宽度和自动布局正确缩放图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆