2012-02-22 55 views
0

如何在没有事务动画的情况下绘制图层?例如,当我设置使用CATransaction的层的内容它工作得很好:CGContextDrawImage without Transaction动画

[CATransaction begin]; 
[CATransaction setValue:(id)kCFBooleanTrue 
       forKey:kCATransactionDisableActions]; 
myLayer.contents = (id)[[imagesTop objectAtIndex:Number]CGImage]; 
[CATransaction commit]; 

,但我需要从委托方法[myLayer setNeedsDisplay]改变内容。下面是代码:

-(void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context 
{ 
    CGContextDrawImage(context, rect, Image.CGImage]);  
} 
+0

你是什么层的代表同样的效果? – sch 2012-02-22 16:54:58

回答

2

CALayer实现setNeedsDisplay方法:

调用此方法将导致接收器重新缓存的内容。这将导致图层接收到drawInContext:,这可能导致代表收到displayLayer:drawLayer:inContext:消息。

...和displayIfNeeded

当接收层将调用display如果它已被标记为需要显示此消息。

如果您将[myLayer displayIfNeeded]换成CATransaction,则可以关闭隐式动画。

+0

对不起,但我需要强制重绘,不仅如果需要 – Andrew 2012-02-22 17:36:41

+1

首先你要将图层标记为需要重绘('[myLayer setNeedsDisplay]')。然后你告诉它如果需要重绘('[myLayer displayIfNeeded]')。由于您已将图层标记为需要重新绘制,因此会立即重绘。请参阅上面引用的“displayIfNeeded”的文档。 – Costique 2012-02-22 17:41:36

+0

它工作得很棒 – Andrew 2012-02-23 14:23:47

1

你也可以继承CALayer和覆盖actionForKey:

- (id <CAAction>) actionForKey: (NSString *) key 
{ 
    if ([key isEqualToString: @"contents"]) 
     return nil; 
    return [super actionForKey: key]; 
} 

此代码禁用内置的动画为contents财产。

或者,您也可以实现通过实施层的委托方法

- (id <CAAction>) actionForLayer: (CALayer *) layer forKey: (NSString *) key 
{ 
    if (layer == myLayer) { 
     if ([key isEqualToString: @"contents"]) 
      return nil; 
     return [[layer class] defaultActionForKey: key]; 
    } 
    return [layer actionForKey: key]; 
}