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

我正在尝试使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(); 

图像resize,但它只是空白。

我正面临与图像重新resize相同的问题。 在互联网上search后,我发现一个有用的方法:

 +(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。 你也可以用你的方式来使用这个类。 希望它的作品。

尝试这个:

 cell.imageView.contentMode = UIViewContentModeScaleAspectFit; 

要么:

 cell.imageView.contentMode = UIViewContentModeScaleAspectFill; 

或者,您可以缩放从url获得的图片。

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