任何人都可以解释为什么重绘到离线CGLayer会导致渲染随着时间的推移而变慢?让我给你展示一个我为了说明问题而创建的测试。CGLayer绘图随着时间的推移变慢
@implementation DrawView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
//setup frame rate monitoring
fps = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
fps.textColor = [UIColor whiteColor];
fps.font = [UIFont boldSystemFontOfSize:15];
fps.text = @"0 fps";
[self addSubview:fps];
frames = 0;
lastRecord = [NSDate timeIntervalSinceReferenceDate];
//create a cglayer and draw the background graphic to it
CGContextRef context = UIGraphicsGetCurrentContext();
cacheLayer = CGLayerCreateWithContext(context, self.bounds.size, NULL);
CGImageRef background = [[UIImage imageNamed:@"background.jpg"] CGImage];
CGContextRef cacheContext = CGLayerGetContext(cacheLayer);
CGContextDrawImage(cacheContext, CGRectMake(0, 0, 768, 1024), background);
//initialize cgimage stamp
stamp = [[UIImage imageNamed:@"stamp.png"] CGImage];
stampTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/60 target:self selector:@selector(stamp) userInfo:nil repeats:YES];
}
return self;
}
- (void) stamp {
//calculate fps
NSTimeInterval interval = [NSDate timeIntervalSinceReferenceDate];
NSTimeInterval diff = interval-lastRecord;
if (diff > 1.0) {
float rate = frames/diff;
frames = 0;
lastRecord = [NSDate timeIntervalSinceReferenceDate];
fps.text = [NSString stringWithFormat:@"%0.1f fps", rate];
}
//stamp the offscreen cglayer with the cgimage graphic
CGRect stampRect = CGRectMake(0, 0, 200, 200);
CGContextRef cacheContext = CGLayerGetContext(cacheLayer);
CGContextDrawImage(cacheContext, stampRect, stamp);
[self setNeedsDisplayInRect:stampRect];
}
- (void)drawRect:(CGRect)dirtyRect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawLayerInRect(context, self.bounds, cacheLayer);
frames++;
}
当运行该测试在ipad的模拟器或设备它开始于40 fps的,并以恒定的速率在10秒的过程中,直到它在像3 fps的运行下降。这是为什么发生?不应该以恒定的帧率运行吗?什么样的解决方案可以让我一次又一次地“印”图像,同时保持恒定的帧率?
+1我通过在初始drawRect调用中创建CGLayer来解决同样的问题。 – 9dan 2011-10-12 09:31:01
对于这个惊人的问题的全面和权威性调查,请查看所有这些包括所有意见: http://stackoverflow.com/questions/4739748/is-there-a-way-to-make-drawrect-工作 - 右 - 现在! ,享受这包括所有的样本项目: http://stackoverflow.com/questions/4786754/mysterious-progressive-slowing-problem-in-run-loop-drawrect 和提供的各种样品溶液项目参与者们。 (注意:很多早期的评论是完全错误的,所以请仔细阅读。) 这真是太神奇了...... Felz是一位真正解决它的家伙。他摇滚。 – Fattie 2016-04-22 19:12:04