12

任何人都知道为什么 CGContextFillPath 在下面的代码片段中不起作用?我正在使用以下代码绘制到 UIImageView。它正确地抚摸了路径,但忽略了 CGContextFillPath。

UIGraphicsBeginImageContext(self.frame.size);
[drawingView.image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
CGContextSetAllowsAntialiasing(UIGraphicsGetCurrentContext(), YES);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
CGContextSetRGBFillColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), firstMovedTouch.x, firstMovedTouch.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
CGContextFillPath(UIGraphicsGetCurrentContext());
drawingView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
4

4 回答 4

27

要解决此问题,请使用以下代码:

CGContextRef context = UIGraphicsGetCurrentContext(); 

CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 1.0);
CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 1.0);
CGContextSetLineJoin(context, kCGLineJoinRound);
CGContextSetLineWidth(context, 8.0);

CGMutablePathRef pathRef = CGPathCreateMutable();

/* do something with pathRef. For example:*/
CGPathMoveToPoint(pathRef, NULL, x, y);
CGPathAddLineToPoint(pathRef, NULL, x, y+100);
CGPathAddLineToPoint(pathRef, NULL, x+100, y+100);
CGPathAddLineToPoint(pathRef, NULL, x+100, y);
CGPathCloseSubpath(pathRef);

CGContextAddPath(context, pathRef);
CGContextFillPath(context);

CGContextAddPath(context, pathRef);
CGContextStrokePath(context);

CGPathRelease(pathRef);
于 2011-07-23T12:40:33.010 回答
19

我相信描边和填充路径的最佳方法是在完成路径设置后添加以下代码行:

    CGContextDrawPath(myContext, kCGPathFillStroke);
于 2012-07-28T12:13:39.520 回答
9

我有同样的麻烦。我发现你不能使用

CGContextStrokePath( UIGraphicsGetCurrentContext() ) 
CGContextFillPath( UIGraphicsGetCurrentContext() ) 

连续:后者将不起作用,因为在路径上提交笔画后,路径将从上下文中删除。

所以,我两次使用了相同的路径;一个用于描边,另一个用于填充。

// ... create a path of CGMutablePathRef ....

CGContextSaveGState( context );
//....fill the path .....
CGContextRestoreGState( context );

CGContextSaveGState ( context );
//....stroke the path .....
CGContextRestoreGState( context );

CFRelease( path );
于 2010-12-03T03:36:30.200 回答
5

我认为您需要先致电CGContextClosePath,然后才能填写路径。我不确定你要画什么,但CGContextFillPath会填充路径内的区域,我在这里只看到一条线。

于 2010-09-28T01:23:15.673 回答