简体   繁体   English

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

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

I am trying to create a single table view cell that displays an image, downloaded from the web, and scaled down to fit the width of the device. 我正在尝试创建一个单一的表格视图单元格,该单元格显示一个图像,该图像是从网上下载的,并按比例缩小以适合设备的宽度。 Part of the problem is that I need to figure out how to resize the cell after the image is downloaded. 问题的一部分是我需要弄清楚下载图像后如何调整单元格的大小。 In other words, I will set a default height while the image is loading, then once the image has loaded, I want to resize the height of the cell. 换句话说,我将在加载图像时设置默认高度,然后在加载图像后,要调整单元格的高度。 I know that I can set the content mode of the image view to "aspect fit" once I specify a fixed width and height, but I'm not sure how to set the constraints programmatically so that the height can remain flexible. 我知道一旦指定了固定的宽度和高度,就可以将图像视图的内容模式设置为“宽高比”,但是我不确定如何以编程方式设置约束以使高度保持灵活。

How can I define these constraints in code? 如何在代码中定义这些约束?

use this code to resize the image after image has been downloaded : 下载图像后,使用此代码调整图像大小:

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

then set your height of your cell with this : 然后使用以下命令设置单元格的高度:

- (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