2013-10-22 50 views
0

我正在使用UIBezierPath繪製Circle。我想在CGLayer上繪製它,這樣我可以在某些事件後通過緩存圓圈並在其上繪製文本(通過調用setNeedsDisplay)。我應該如何在CGContextRef上繪製UIBezierPath。我下面如何在CGLayer上繪製UIBezierPath?

- (void)drawRect:(CGRect)rect 
{ 
    // Drawing code 
    static CGLayerRef sTextLayer = NULL; 
    CGContextRef ctx = UIGraphicsGetCurrentContext(); 
    CGRect textBounds = CGRectMake(0, 0, 200, 100); 
    if (sTextLayer == NULL) { 
     sTextLayer = CGLayerCreateWithContext(ctx, textBounds.size, NULL); 
     CGContextRef textCtx = CGLayerGetContext(sTextLayer); 
     CGContextSetRGBFillColor (textCtx, 1.0, 0.0, 0.0, 1); 
     UIGraphicsPushContext(textCtx); 

     // Draw circle 
     UIBezierPath *circle = [UIBezierPath bezierPathWithOvalInRect:textBounds]; 
     [[UIColor blackColor] setFill]; 
     circle.lineWidth = 2.0; 
     [circle fill]; 

     UIGraphicsPopContext(); 
    } 

    if (self.drawString) { 
     UIFont *font = [UIFont systemFontOfSize:13.0]; 
     NSString *string = @"HAPPY BIRTHDAY"; 
     [string drawInRect:textBounds withFont:font]; 
    } 
} 
+0

您可以查看示例代碼並在您的項目中實現 – Sport

回答

0

代碼從貝塞爾曲線獲得CGPath,然後繪製使用CGContextAddPathCGContextStrokePath。您也可以使用CGContextSetStrokeColorWithColor

0

您可以:

  1. 避免使用CGLayerRef乾脆,只是有drawRectUIBezierPathfill方法(或Wain的建議,採用核心圖形功能繪製圓形)。

  2. 添加CAShapeLayer,並設置其pathUIBezierPathCGPathRef,然後添加文本作爲CATextLayerUILabel子視圖(在這種情況下,你不需要drawRect實現的話)。

我推斷你擔心重繪圓的效率,但是當你渲染文本時,它可能需要重新渲染圓。您可以隨時保存對UIBezierPath的引用或製作快照,但我不確定這是否值得。你可以對它進行基準測試並查看