核心图形CGContextClip - Xcode

时间:2012-07-10 07:01:51

标签: xcode core-graphics clipping

开始了解核心图形。我正在绘制一个填充和描边的路径,但我无法将其剪辑。谁能告诉我这里我做错了什么?

此代码位于我的UIView子类的drawRect方法中。

//Draw a closed path with rounded corners, a fill and a stroke.
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 4.0);
CGContextSetStrokeColorWithColor(context,[UIColor blueColor].CGColor);
CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
//fill
CGContextMoveToPoint(context, 10, 10);
CGContextAddLineToPoint(context, 10, 100);
CGContextAddArcToPoint(context, 10,140, 30,140, 20);
CGContextAddLineToPoint(context, 200, 140);
CGContextAddArcToPoint(context, 240,140, 240,100, 20);
CGContextAddLineToPoint(context, 240, 10);
CGContextClosePath(context);
CGContextFillPath(context);
//stroke
CGContextMoveToPoint(context, 10, 10);
CGContextAddLineToPoint(context, 10, 100);
CGContextAddArcToPoint(context, 10,140, 30,140, 20);
CGContextAddLineToPoint(context, 200, 140);
CGContextAddArcToPoint(context, 240,140, 240,100, 20);
CGContextAddLineToPoint(context, 240, 10);
CGContextClosePath(context);
CGContextStrokePath(context);
CGContextBeginPath(context);
//clip??
CGContextMoveToPoint(context, 10, 10);
CGContextAddLineToPoint(context, 10, 100);
CGContextAddArcToPoint(context, 10,140, 30,140, 20);
CGContextAddLineToPoint(context, 200, 140);
CGContextAddArcToPoint(context, 240,140, 240,100, 20);
CGContextAddLineToPoint(context, 240, 10);
CGContextClosePath(context);
CGContextClip(context);

2 个答案:

答案 0 :(得分:1)

您应该在执行应剪裁的绘图之前剪切上下文,然后在

之后恢复上下文

答案 1 :(得分:0)

您应该在CGContextClip之前和CGContextStrokePath之后使用CGContextClosePath。这就够了。无需编写额外的代码。尝试像下面那样......

    CGContextClosePath(context);
    CGContextClip(context);
    CGContextStrokePath(context);

我认为这会对你有所帮助。