在drawRect中优化CGContextDrawRadialGradient

4
在我的iPad应用中,有一个UITableView,每次选择新的单元格时都会分配/初始化一个UIView子类。我已经重写了这个UIView中的drawRect:方法来绘制径向渐变,它能正常工作,但是性能受到影响 - 当选中单元格时,与使用.png文件背景相比,UIView编程绘制渐变需要更长时间。是否有任何方法可以“缓存”我的drawRect:方法或生成的渐变以提高性能?我宁愿使用drawRect:而不是.png文件。我的方法如下:
- (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);
}

谢谢!

1个回答

2

您可以将图形渲染到上下文中,然后将其存储为UIImage。 这个答案 可以帮助您入门:

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

Since it seems that you want to create shapes to store them and draw later, it appears reasonable to create the shapes as UIImage and draw them using UIImageView. UIImage can be stored directly in an NSArray.

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

1) create a bitmap context

UIGraphicsBeginImageContextWithOptions(size, opaque, scale);

2) get the context

CGContextRef context = UIGraphicsGetCurrentContext();

3) draw whatever you need

4) export the context into an image

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

5) destroy the context

UIGraphicsEndImageContext();

6) store the reference to the image

[yourArray addObject:image];

Repeat for each shape you want to create.

For details see the documentation for the above mentioned functions. To get a better understanding of the difference between drawing in drawRect: and in arbitrary place in your program and of working with contexts in general, I would recommend you read the Quartz2D Programming Guide, especially the section on Graphics Contexts.


据我所知,Objective-C没有高亮提示。普通的C语言可以吗? - Zev Eisenberg
我已经认识到我的错误,并会悔改 :) (感谢编辑) - Zev Eisenberg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接