为什么在描边路径颜色之前填充路径颜色时,CGContext没有绘制任何内容。

3

像这样的代码

UIGraphicsBeginImageContextWithOptions(CGSizeMake(100, 100), NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(context, 5, 5);
CGContextAddLineToPoint(context, 100, 100);
CGContextSetLineWidth(context, 5);
CGContextSetFillColorWithColor(context, [UIColor blueColor].CGColor);
CGContextFillPath(context);
CGContextSetStrokeColorWithColor(context, [UIColor grayColor].CGColor);
CGContextStrokePath(context);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

当我删除填充颜色时,图像是正确的。 但我不明白为什么添加填充颜色后图像就消失了?


1
你还没有创建路径,所以填充可能会填满整个上下文。你需要创建一个封闭的路径来进行填充。 - rmaddy
1、如果我没有路径,如何让描边路径生效呢? 2、如果我在描边路径之后放置了fillPath方法,那么图像就是正确的。这是怎么解释的呢? - frank
1
  1. 你没有一个可以填充的封闭路径,只有一条可以描边的线。
  2. 最有可能的是描边该线会使其成为一个封闭路径,从而可以填充它。
- rmaddy
@rmaddy 感谢您的回答。 - frank
1个回答

0
问题在于如何在上下文中进行绘制。
请尝试以下操作:
    CGRect rect = CGRectMake(0.0,0.0, 100, 100);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    //Set background color
    CGContextSetRGBFillColor(context, 1.0,1.0,1.0,1.0);
    CGContextFillRect(context,rect);
    CGContextSetLineWidth(context, 2.0);
    CGContextSetStrokeColorWithColor(context, [UIColor grayColor].CGColor);
    CGContextSetFillColorWithColor(context, [UIColor blueColor].CGColor);
    CGContextMoveToPoint(context, 5, 5);
    CGContextAddLineToPoint(context, 100, 100);
    CGContextStrokePath(context);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

现在

 _testImage.image = image;

你将会得到结果。请告诉我您的反馈意见。


它可以工作。但是你错过了一行 CGContextFillPath(context); 如果你在 CGContextStrokePath(context) 之前添加这行代码,图像仍然为空... 我感到困惑。如何填充路径会影响描边路径,以及填充和描边顺序如何影响结果。 - frank
你可以尝试在相同的位置使用CGContextDrawPath(context, kCGPathFillStroke)而不是CGContextStrokePath(context)。我认为会起作用。 - rejusss

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接