简单一个例子 UITableViewCell的异步绘制
//异步绘制 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ CGRect rect = [_data[@"frame"] CGRectValue]; UIGraphicsBeginImageContextWithOptions(rect.size, YES, 0); CGContextRef context = UIGraphicsGetCurrentContext(); //整个内容的背景 [[UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1] set]; CGContextFillRect(context, rect); //转发内容的背景 if ([_data valueForKey:@"subData"]) { [[UIColor colorWithRed:243/255.0 green:243/255.0 blue:243/255.0 alpha:1] set]; CGRect subFrame = [_data[@"subData"][@"frame"] CGRectValue]; CGContextFillRect(context, subFrame); [[UIColor colorWithRed:200/255.0 green:200/255.0 blue:200/255.0 alpha:1] set]; CGContextFillRect(context, CGRectMake(0, subFrame.origin.y, rect.size.width, .5)); } { //名字 float leftX = SIZE_GAP_LEFT+SIZE_AVATAR+SIZE_GAP_BIG; float x = leftX; float y = (SIZE_AVATAR-(SIZE_FONT_NAME+SIZE_FONT_SUBTITLE+6))/2-2+SIZE_GAP_TOP+SIZE_GAP_SMALL-5; [_data[@"name"] drawInContext:context withPosition:CGPointMake(x, y) andFont:FontWithSize(SIZE_FONT_NAME) andTextColor:[UIColor colorWithRed:106/255.0 green:140/255.0 blue:181/255.0 alpha:1] andHeight:rect.size.height]; //时间+设备 y += SIZE_FONT_NAME+5; float fromX = leftX; float size = [UIScreen screenWidth]-leftX; NSString *from = [NSString stringWithFormat:@"%@ %@", _data[@"time"], _data[@"from"]]; [from drawInContext:context withPosition:CGPointMake(fromX, y) andFont:FontWithSize(SIZE_FONT_SUBTITLE) andTextColor:[UIColor colorWithRed:178/255.0 green:178/255.0 blue:178/255.0 alpha:1] andHeight:rect.size.height andWidth:size]; } //将绘制的内容以图片的形式返回,并调主线程显示 UIImage *temp = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); dispatch_async(dispatch_get_main_queue(), ^{ if (flag==drawColorFlag) { postBGView.frame = rect; postBGView.image = nil; postBGView.image = temp; } } //内容如果是图文混排,就添加View,用CoreText绘制 [self drawText]; }}
上面代码放在自定义 draw方法里 或者 去掉GCD多线程,直接放到 drawRect方法里,重写它,因为drawRect本来就是异步绘制