2013-10-22 45 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的引用或制作快照,但我不确定这是否值得。你可以对它进行基准测试并查看