mtm*_*ock 5 cocoa calayer nsbezierpath
我正在制作一个自定义的NSView对象,其中包含一些经常更改的内容,而另一些则不经常更改.事实证明,变化较少的部分需要花费最多的时间来绘制.我想要做的是将这两个部分呈现在不同的层中,以便我可以单独更新其中一个,从而使我的用户免于缓慢的用户界面.
我该怎么做呢?我没有找到很多这方面的好教程,也没有谈论在CALayer上渲染NSBezierPaths.想法有人吗?
您的预感是正确的,这实际上是优化绘图的绝佳方法。我自己做过,我有一些大型静态背景,我想避免当元素移动到顶部时重新绘制。
您所需要做的就是CALayer
为视图中的每个内容项添加对象。要绘制图层,您应该将视图设置为每个图层的委托,然后实现该drawLayer:inContext:
方法。
在该方法中,您只需绘制每一层的内容:
- (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
}
Run Code Online (Sandbox Code Playgroud)
当你想更新其中一层的内容时,只需调用[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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1073 次 |
最近记录: |