核心图形CGContextClip-Xcode

核心图形CGContextClip-Xcode,xcode,core-graphics,clipping,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); CGContextSetStrok

开始理解核心图形。我正在绘制一条带有填充和笔划的路径,但我无法将其剪裁。有人能告诉我我做错了什么吗

此代码位于我的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);

您应该在绘制应剪裁的图形之前剪裁上下文,然后在
CGContextClip
之前和
CGContextClosePath
之后使用
CGContextClip
恢复上下文。够了。不需要编写额外的代码。试着这样做如下

    CGContextClosePath(context);
    CGContextClip(context);
    CGContextStrokePath(context);
我想这对你会有帮助的