繁体   English   中英

如何以编程方式将UIImageView缩放为固定宽度和灵活高度?

[英]How to programmatically scale a UIImageView to a fixed width and flexible height?

我正在尝试创建一个单一的表格视图单元格,该单元格显示一个图像,该图像是从网上下载的,并按比例缩小以适合设备的宽度。 问题的一部分是我需要弄清楚下载图像后如何调整单元格的大小。 换句话说,我将在加载图像时设置默认高度,然后在加载图像后,要调整单元格的高度。 我知道一旦指定了固定的宽度和高度,就可以将图像视图的内容模式设置为“宽高比”,但是我不确定如何以编程方式设置约束以使高度保持灵活。

如何在代码中定义这些约束?

下载图像后,使用此代码调整图像大小:

//example
//UIImageView *yourImageView = [self imageWithImage:yourDownloadedImage scaledToWidth:CGRectGetWidth(self.view.frame)]


- (UIImage*)imageWithImage: (UIImage*) sourceImage scaledToWidth:(float)i_width{
float oldWidth = sourceImage.size.width;

if (oldWidth <= self.view.frame.size.width) {
    return sourceImage; // remove this line if you want the image width  follow your screen width
}
float scaleFactor = i_width / oldWidth;
float newHeight = sourceImage.size.height * scaleFactor;

UIGraphicsBeginImageContext(CGSizeMake(i_width, newHeight));
[sourceImage drawInRect:CGRectMake(0, 0, i_width, newHeight)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}

然后使用以下命令设置单元格的高度:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath]; // i'm using static cell so i call this
    return [self calculateHeightForConfiguredSizingCell:cell];
}

- (CGFloat)calculateHeightForConfiguredSizingCell:(UITableViewCell *)sizingCell {
[sizingCell layoutIfNeeded];

CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return size.height;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM