2012-04-16 71 views
0

我有一个自定义图层,它是其他东西的子图层。问题是,我的图层在drawLayer:inContext:之前无法知道它的大小。在drawLayer中更新自定义CALayer的边界:inContext:

当我不要更改我的图层的边界/框架一切都完美绘制。

当我添加行来改变框架/边界,我的背景看起来很完美,但我的内容不存在。它看起来像内容是削减原来的边界,而不是新的(更大的)边界,所以我什么都看不到背景。

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context { 
    CGFloat initialGraphContentsWidth = graph.frame.size.width - graph.leftMargin; 
    CGFloat initialGraphContentsHeight = graph.frame.size.height - graph.bottomMargin - graphHelper.topMargin; 

    self.frame = CGRectMake(0, 0, initialGraphContentsWidth, initialGraphContentsHeight); 
    self.position = CGPointMake(graphHelper.leftMargin + 1, graphHelper.topMargin + 1); 
    self.backgroundColor = [UIColor greenColor].CGColor; 

    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor); 
    CGContextAddRect(context, CGRectMake(0, 0, 20, 20)); 
} 

那么如何动态改变我的界限,并仍然让我的内容出现?

我试着设置了一个持续时间为0的CATransaction,但是没有做任何事情。

回答

0

您是否在更新帧/边界后尝试呼叫setNeedsDisplay?因此,例如

,如果你有一个叫CALayerlayer,你可以尝试以下方法:

layer.frame = CGRectMake(20, 40, 100, 300); 
// tell the layer that it needs to refreshed 
[layer setNeedsDisplay]; 
+0

'setNeedsDisplay'导致'drawLayer:inContext'被调用。因此,调用'setNeedsDisplay'会导致无限循环,最好的Apple代码会识别这个问题并忽略这个调用。 – DBD 2012-04-23 12:14:42