我正在尝试创建一个 TableView 单元格,该单元格显示从网络下载的图像,并按比例缩小以适合设备的宽度。部分问题是我需要弄清楚如何在下载图像后调整单元格的大小。换句话说,我将在加载图像时设置默认高度,然后一旦加载图像,我想调整单元格的高度。我知道一旦指定固定的宽度和高度,我就可以将 ImageView 的内容模式设置为“宽高比适合”,但我不确定如何以编程方式设置约束以使高度保持灵活。
如何在代码中定义这些约束?
最佳答案
下载图片后使用此代码调整图片大小:
//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;
}
关于ios - 如何以编程方式将 UIImageView 缩放到固定宽度和灵活高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34344658/