【问题标题】:Why The CGContext draw nothing when I fill path color before stroke path color.为什么当我在描边路径颜色之前填充路径颜色时,CGContext 什么也不画。
【发布时间】:2015-07-07 04:09:03
【问题描述】:

这样的代码

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、如果我没有路径,笔划路径如何生效。 2、如果我把fillPath方法放在stoke路径之后,那么图像是正确的。这要怎么解释?
  • 1.您没有可以填充的封闭路径。你只有一条线,你可以抚摸。 2. 最有可能抚摸线条使其成为一条封闭路径,让您可以填充它。
  • @rmaddy 感谢您的回答。

标签: ios cgcontext cgpath


【解决方案1】:

问题在于你如何在上下文中绘制。

请尝试以下方法:

    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)之前加上这行,图片还是空的……感觉很迷茫。填充路径如何影响笔触路径以及填充和笔触顺序如何影响结果。
  • 你能不能在同一个位置用 CGContextDrawPath(context, kCGPathFillStroke) 代替 CGContextStrokePath(context) 。我认为会工作..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 2015-06-02
相关资源
最近更新 更多