Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView Lagging due to Shadows and Borders

I have the following code to add a border colour and drop shadow to the background of my UITableViewCell. My problem is that this code causes a huge lag on the tableView itself.

Please can you tell me how I can optimise my code, preventing the lag of the UITableView?

if ([cell viewWithTag:012] == nil && comment.isReply == NO) {
    UIImageView *iv = [[[UIImageView alloc] initWithFrame:frame] autorelease];
    [iv setImage:[UIImage imageNamed:@"paper"]];
    [iv setTag:012];
    [cell insertSubview:iv atIndex:0];

    [iv.layer setBorderWidth:1.0];
    [iv.layer setBorderColor:[[UIColor whiteColor] CGColor]];

    [iv.layer setShadowColor:[[UIColor blackColor] CGColor]];
    [iv.layer setShadowOffset:CGSizeMake(0, 1)];
    [iv.layer setShadowOpacity:0.75];

}

else if ([cell viewWithTag:012] == nil && comment.isReply == YES) {

    frame.origin.x += 35;

    UIImageView *iv = [[[UIImageView alloc] initWithFrame:frame] autorelease];
    [iv setImage:[UIImage imageNamed:@"paper"]];
    [iv setTag:012];
    [cell insertSubview:iv atIndex:0];

    UIImage *arrow = [UIImage imageNamed:@"arrow"];
    UIImageView *ivs = [[[UIImageView alloc] initWithFrame:CGRectMake(-12, ([cell frame].size.width / 2) + ([arrow size].width/2) , arrow.size.width, arrow.size.height)] autorelease];
    [cell addSubview:ivs];

    [iv.layer setBorderWidth:1.0];
    [iv.layer setBorderColor:[[UIColor whiteColor] CGColor]];

    [iv.layer setShadowColor:[[UIColor blackColor] CGColor]];
    [iv.layer setShadowOffset:CGSizeMake(0, 0)];
    [iv.layer setShadowOpacity:0.75];

}
like image 390
max_ Avatar asked Nov 30 '11 22:11

max_


1 Answers

In addition to the other optimization advice here, specifying a shadowPath on your CALayer will improve shadow drawing performance. You could determine a path for the shadow with something like this...

iv.layer.shadowPath = [UIBezierPath bezierPathWithRect:iv.bounds].CGPath;

You may also want to look into the shouldRasterize bit on CALayer. This causes the layer to be pre-rendered as a bitmap. Make sure to also provide a rasterizationScale that matches your device if you go this route.

cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
like image 84
Mark Adams Avatar answered Sep 29 '22 14:09

Mark Adams