2012-04-16 70 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