我正在制作一个自定义 NSView 对象,其中一些内容经常更改,而另一些内容则很少更改。事实证明,变化较少的部分需要花费最多的时间来绘制。我想做的是将这两个部分渲染在不同的层中,以便我可以分别更新其中一个或另一个,从而使我的用户免受缓慢的用户界面的困扰。
我该怎么做呢?我还没有找到很多关于此类事情的好的教程,也没有一个讨论在 CALayer 上渲染 NSBezierPaths。有人有想法吗?
您的预感是正确的,这实际上是优化绘图的绝佳方法。我自己做过,我有一些大型静态背景,我想避免当元素移动到顶部时重新绘制。
您需要做的就是添加CALayer
视图中每个内容项的对象。要绘制图层,您应该将视图设置为每个图层的委托,然后实现drawLayer:inContext:
method.
在该方法中,您只需绘制每一层的内容:
- (void)drawLayer:(CALayer*)layer inContext:(CGContextRef)ctx
{
if(layer == yourBackgroundLayer)
{
//draw your background content in the context
//you can either use Quartz drawing directly in the CGContextRef,
//or if you want to use the Cocoa drawing objects you can do this:
NSGraphicsContext* drawingContext = [NSGraphicsContext graphicsContextWithGraphicsPort:ctx flipped:YES];
NSGraphicsContext* previousContext = [NSGraphicsContext currentContext];
[NSGraphicsContext setCurrentContext:drawingContext];
[NSGraphicsContext saveGraphicsState];
//draw some stuff with NSBezierPath etc
[NSGraphicsContext restoreGraphicsState];
[NSGraphicsContext setCurrentContext:previousContext];
}
else if (layer == someOtherLayer)
{
//draw other layer
}
//etc etc
}
当你想更新其中一层的内容时,只需调用[yourLayer setNeedsDisplay]
。然后,这将调用上面的委托方法来提供图层的更新内容。
请注意,默认情况下,当您更改图层内容时,核心动画会为新内容提供良好的淡入淡出过渡。但是,如果您自己处理绘图,您可能不希望这样做,因此为了防止图层内容更改时动画的默认淡入淡出,您还必须实现actionForLayer:forKey:
委托方法并通过返回 null 操作来阻止动画:
- (id<CAAction>)actionForLayer:(CALayer*)layer forKey:(NSString*)key
{
if(layer == someLayer)
{
//we don't want to animate new content in and out
if([key isEqualToString:@"contents"])
{
return (id<CAAction>)[NSNull null];
}
}
//the default action for everything else
return nil;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)