从 URL 加载 UIImage 时在 UITableViewCell 中设置 UIImageView 大小?

Set UIImageView Size in UITableViewCell when UIImage loaded from URL?(从 URL 加载 UIImage 时在 UITableViewCell 中设置 UIImageView 大小?)

本文介绍了从 URL 加载 UIImage 时在 UITableViewCell 中设置 UIImageView 大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将图像从 URL 加载到 uiimage 中,然后将这些图像添加到 uitableviewcell uiimageview,如下面的代码.我不知道图像大小,但需要在 tableviewcell 图像中强制它们为 40x40.图像在 uitableview 中以不同的宽度不断加载.

Loading images from URL into a uiimage and then adding those images to a uitableviewcell uiimageview, like below code. I do not know the image sizes, but need to force them to be 40x40 in the tableviewcell image. The images keep loading with different widths in the uitableview.

阅读与 uiimage 大小/缩放相关的其他帖子,但这些解决方案对我不起作用.我想这是因为我使用的是 uitableviewcell 中包含的 uiimageview 而不是创建自己的 uiimageview.

Read through other posts related to uiimage sizing/scaling, but those solutions don't work for me. I am thinking it's because I am using the uiimageview included in uitableviewcell vs creating my own uiimageview.

这是代码>

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cell = [[UITableViewCell alloc] init];

ItemForSale *item = [listOfItems objectAtIndex:indexPath.row];
cell.textLabel.text = item.name;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.font = [UIFont systemFontOfSize:14];

NSURL *url = [NSURL URLWithString: item.imgPath];
UIImage *thumbnail = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
if (thumbnail == nil) {
    thumbnail = [UIImage imageNamed:@"noimage.png"] ;
}
cell.imageView.image = thumbnail;
cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
cell.imageView.frame = CGRectMake(0, 0, 40, 40);
cell.imageView.autoresizingMask = UIViewAutoresizingNone;
cell.imageView.clipsToBounds = YES;

return cell;

}

我尝试过设置内容模式(尝试了aspectfill 和aspect fit),尝试重置框架,设置autoresizingmask,clipTobound.没有任何改变.

I've tried setting content mode (tried both aspectfill and aspect fit), tried resetting the frame, setting autoresizingmask, clipTobound. none of it changed a thing.

推荐答案

看苹果示例项目LazyTableImages"找到答案

Found the answer looking at Apples example project "LazyTableImages"

NSURL *url = [NSURL URLWithString: item.imgPath];
UIImage *thumbnail = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
if (thumbnail == nil) {
    thumbnail = [UIImage imageNamed:@"noimage.png"] ;
}
CGSize itemSize = CGSizeMake(40, 40);
UIGraphicsBeginImageContext(itemSize);
CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
[thumbnail drawInRect:imageRect];
cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return cell;

这篇关于从 URL 加载 UIImage 时在 UITableViewCell 中设置 UIImageView 大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:从 URL 加载 UIImage 时在 UITableViewCell 中设置 UIImageView 大小?

基础教程推荐