如何在UITableViewCell中调整图像大小?

时间:2014-08-09 01:10:12

标签: ios uitableview

我正在尝试制作一个Xcode应用程序,其中包含一个从JSON文件加载数据的列表。它基本上有标题,副标题和缩略图。当应用程序加载时,图像与单元格一样大。我想要将图像调整到一定的大小,或者在单元格之间留出一些额外的空间。这是我目前的代码:

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

static NSString *CellIdentifier = @"TableCell";


UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];


NSDictionary *tempDictionary= [self.googlePlacesArrayFromAFNetworking objectAtIndex:indexPath.row];

NSURL *url = [NSURL URLWithString:[tempDictionary objectForKey:@"icon"]];
NSData *data = [NSData dataWithContentsOfURL:url];
cell.imageView.image = [UIImage imageWithData:data];
CALayer * l = [cell.imageView layer];
[l setCornerRadius:13];
[l setBorderWidth:0.5];
[l setBorderColor:[[UIColor lightGrayColor] CGColor]];
cell.imageView.layer.masksToBounds = YES;
...}

感谢您的帮助。

更新:我发现了这个:

 UIImage *thumbnail = [UIImage imageWithData: [NSData dataWithContentsOfURL :url]];

CGSize itemSize = CGSizeMake(30, 30);
UIGraphicsBeginImageContext(itemSize);
CGRect imageRect = CGRectMake(30.0, 30.0, itemSize.width, itemSize.height);
[thumbnail drawInRect:imageRect];
cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

图像调整大小,但它只是空白。

2 个答案:

答案 0 :(得分:1)

试试这个:

cell.imageView.contentMode = UIViewContentModeScaleAspectFit;

或者:

cell.imageView.contentMode = UIViewContentModeScaleAspectFill;

或者,您可以缩放从网址获得的图像。

CGFloat scale = 10.0f;    // adjust this number
UIImage *image = [UIImage imageWithData:
                                  [NSData dataWithContentsOfURL:url]
                                  scale:scale];
cell.imageView.image = image;

答案 1 :(得分:1)

我在图像重新调整大小时遇到​​了同样的问题。在互联网上搜索后,我找到了一个有用的方法:

+(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
UIGraphicsBeginImageContext( newSize );
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}

这将返回图像大小。 在我的例子中,我创建了一个Helper类,在 Helper.h 中,我将此方法声明为类方法,以便我可以在UITableView中调用它。我在 Helper.m 中实现了这种方法。

在cellForRowAtIndexPath方法中:

cell.imageView.image = [Helper imageWithImage:***Your Image here*** scaledToSize:CGSizeMake(ImageWidth,ImageHeight)];

不要忘记在TableView类中导入Helper.h。 您也可以按照自己的方式使用此课程。 希望它有效。