【问题标题】:Draw with core graphics only inside the circle仅在圆圈内使用核心图形绘制
【发布时间】:2015-05-19 15:51:02
【问题描述】:

我需要实现一个实时绘制的 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];
}

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

不想要的行为是这样的:

【问题讨论】:

  • 可以发截图吗?
  • @ZeMoon 请查看已编辑的问题
  • 这是 UIView 的子类吗?
  • @ZeMoon 是的,但圆圈是从边界缩进绘制的
  • 先剪辑,然后绘制。剪裁会影响之后发生的所有绘图,如果您以后需要绘制任何不想被剪裁的东西,您也可以保存上下文然后恢复。

标签: ios objective-c core-graphics


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 2012-03-23
    • 1970-01-01
    相关资源
    最近更新 更多