UITableView中的圆形UIImages导致速度减慢

时间:2012-03-11 21:48:47

标签: ios uitableview uiimage

当我尝试在所有自定义UITableViewCells中对UIImages进行舍入时,UITableView的滚动速度显着降低且不流畅。还有更好的方法吗?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell.profileLabel.text = [[demoArray objectAtIndex:[indexPath row]] objectForKey:@"name"];
 cell.imageView.image = [UIImage imageNamed:[[demoArray objectAtIndex:[indexPath row]] objectForKey:@"image"]];
    cell.imageView.layer.cornerRadius = 9.0;
    cell.imageView.layer.masksToBounds = YES;    
    return cell;
}

2 个答案:

答案 0 :(得分:3)

虽然调整图层的圆角半径肯定很方便,但它可能会受到一些性能损失。就个人而言,我会这样做非常直接。

在任何图形编辑器中创建叠加层 - 使用与单元格背景相同的颜色填充角落以使它们与所需形状匹配。现在为您的单元格添加一个新的UIImageView,将其直接放置在您的图片上,并确保叠加层保持在最顶层。

答案 1 :(得分:0)

1)您可以在viewDidLoad中创建圆形图像(或者当您的数据准备就绪时)并将它们保存到临时数组中。要做到这一点,你就像现在一样创建它。然后将视图内容捕获到新图像中。然后,在没有动态遮罩的情况下,在tableview中显示新创建的图像。

要将viewcontents保存到图像中,您可以使用以下代码:

- (UIImage*) screenshotOfView: (UIView*) view
{
    UIGraphicsBeginImageContext(view.frame.size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return viewImage;
}
好的,我会更具体。目前,demoArray充满了数据。迭代该数组并预渲染图像。多数民众赞成你如何做(使用上述方法):

for(NSDictionary* dictionary in demoArray)
{
    UIImage* originalImage = [UIImage imageNamed:[dictionary objectForKey:@"image"]];

    UIImageView* tmpImageView = [[UIImageView alloc] initWithImage: originalImage];
    tmpImageView.layer.cornerRadius = 9.0;
    tmpImageView.layer.masksToBounds = YES;

    UIImage* roundedImage = [self screenshotOfView: tmpImageView];
    [dictionary setObject: roundedImage forKey: @"roundedImage"];
}

然后在您的cellForTableRow方法中,您只需使用该图片:

cell.imageView.image = [UIImage imageNamed:[[demoArray objectAtIndex:[indexPath row]] objectForKey:@"roundedImage"]];

(此代码未经过测试,只是将其写下来......)

2)另一个可能更快的解决方案是在drawRect:内的tableViewCell子类中绘制图像(通过CoreGraphics屏蔽),但这样更复杂。

3)按照Bartosz Ciechanowski的回答,您可以为每个尺寸动态创建所需的overlayImage,即使用CorGraphics。但第一种解决方案可能是最简单的。