Optimize CGContextDrawRadialGradient in drawRect:

In my iPad app, I have a UITableView that selects / introduces a subclass of UIView every time a new cell is selected. I overridden drawRect: in this UIView, to draw a radial gradient, and it works fine, but performance suffers - when a cell is listened, UIView takes significantly longer to draw the gradient programmatically, rather than using .png for the background. Is there a way to "cache" my drawRect: method or the gradient that it creates to improve performance? I prefer to use drawRect: instead of .png. My method is as follows:

 - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); size_t gradLocationsNum = 2; CGFloat gradLocations[2] = {0.0f, 1.0f}; CGFloat gradColors[8] = {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.5f}; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, gradColors, gradLocations, gradLocationsNum); CGColorSpaceRelease(colorSpace); CGPoint gradCenter = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)); float gradRadius = MIN(self.bounds.size.width , self.bounds.size.height) ; CGContextDrawRadialGradient (context, gradient, gradCenter, 0, gradCenter, gradRadius, kCGGradientDrawsAfterEndLocation); CGGradientRelease(gradient); } 

Thank!

+3
objective-c drawrect
Jul 10 '12 at 20:15
source share
1 answer

You can display graphics in context and then save them as UIImage. This answer should start:

drawRect: is a method on UIView , used to create the view itself, and not to pre-create graphic objects.

Since it seems that you want to create shapes for storing them and draw them later, it seems reasonable to create shapes like UIImage and draw them using UIImageView . UIImage can be saved directly to NSArray .

To create images, do the following (in the main queue, not in drawRect :):

1) create a bitmap context

 UIGraphicsBeginImageContextWithOptions(size, opaque, scale); 

2) get context

 CGContextRef context = UIGraphicsGetCurrentContext(); 

3) draw everything you need

4) export context to image

 UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 

5) destroy the context

 UIGraphicsEndImageContext(); 

6) save the link to the image

 [yourArray addObject:image]; 

Repeat for each shape you want to create.

See the documentation for the above features for more details. To better understand the difference between a drawing in drawRect: and in an arbitrary place in your program and work with contexts in general, I would recommend that you read the Quartz2D Programming Guide , especially the "Graphic Contexts" section.

+2
Nov 16 '12 at 20:56
source share
— -



All Articles