gpt4 book ai didi

objective-c - 优化drawRect中的CGContextDrawRadialGradient :

转载 作者:搜寻专家 更新时间:2023-10-30 19:46:32 24 4
gpt4 key购买 nike

在我的 iPad 应用程序中,我有一个 UITableView,它会在每次选择新单元格时分配/初始化一个 UIView 子类。我已经覆盖了此 UIView 中的 drawRect: 以绘制径向渐变并且它工作正常,但性能受到影响 - 当点击一个单元格时,UIView 需要更长的时间以编程方式绘制渐变,而不是使用 .png 作为背景。有没有办法“缓存”我的 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);
}

谢谢!

最佳答案

您可以将图形渲染到上下文中,然后将其存储为 UIImage。 This answer应该让你开始:

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 - 优化drawRect中的CGContextDrawRadialGradient :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11421222/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com