仅在圆圈内

时间:2015-05-08 09:06:26

标签: ios objective-c core-graphics

我需要实现一个XY动态图 - 它是实时绘制的。我有两种方法,首先我用填充颜色绘制圆圈:

- (void) drawCircleWithFillColorComponent:(float)value {
    CGPoint center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2);
    CGFloat radius = MIN(center.x, center.y)-5.f;
    UIBezierPath *path = [self bezierArcWithCenter:center
                                        startAngle:0
                                          endAngle:M_PI*2
                                            radius:radius];
    [[UIColor whiteAppColor] setStroke];
    [[self colorWithValue:currentValue] setFill];
    [path setLineWidth:1.f];
    [path fill];
    [path stroke];
} 

而不是我绘制图表:

- (void)drawHistoryInContext:(CGContextRef)context bounds:(CGRect)bounds {
    CGFloat value;

    UIBezierPath *graph = [UIBezierPath new];

    for (NSUInteger counter = 0; counter < historyArray.count; counter++) {
        value = [historyArray[counter] floatValue];
        if (counter == 0) {
            [graph moveToPoint:CGPointMake(bounds.origin.x+5+bounds.size.width/2/50, bounds.origin.y+bounds.size.height/2-(value-1)*bounds.size.height/12)];
        } else {
            [graph addLineToPoint:CGPointMake(bounds.origin.x+5+(float)counter/(float)(50-1)*bounds.size.width/2, MAX(bounds.origin.y+bounds.size.height/2-(value-1)*bounds.size.height/12,0))];
        }
    }

    [graph setLineWidth:2.f];
    [[UIColor lightBlueAppColor] setStroke];
    [graph stroke];
}

问题是 - 图表的背景是一个圆圈。所以我需要在圆圈内剪切图形。现在绘制图形的区域是一个矩形 - 有时图形线显示在圆形边框之外。如何剪切图表?

不受欢迎的行为是这样的:

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以剪切上下文,具体取决于您的drawRect:实施。本质上,在绘制图形线之前剪切,然后绘制。剪切会影响之后发生的所有绘图,您还可以保存上下文(使用CGContextSaveGState),然后恢复(使用CGContextRestoreGState),如果您需要稍后绘制任何不想剪裁的内容。