【问题标题】:Cannot fill CGContext for simple shape无法为简单形状填充 CGContext
【发布时间】:2012-06-23 23:14:47
【问题描述】:

以下方法应该创建一个 FILLED 三角形图像,但它只创建一个轮廓。 为什么它不填充?和这个一起疯了。我希望它得到答复,以便下一个为此苦苦挣扎的可怜人可以清除障碍并节省一个小时的生命。

这是我写的方法:

+ (UIImage *)triangleWithSize:(CGSize)imageSize
{
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
    CGContextRef context = UIGraphicsGetCurrentContext();    
    CGContextSetShouldAntialias(context, YES);

    // set parameters
    CGContextSetLineWidth(context, 1);
    CGContextSetStrokeColorWithColor(context, [UIColor yellowColor].CGColor);
    CGContextSetFillColorWithColor(context, [UIColor yellowColor].CGColor);

    // draw triangle
    CGContextBeginPath(context);
    CGContextMoveToPoint(context, imageSize.width, 0);
    CGContextAddLineToPoint(context, imageSize.width, imageSize.height);
    CGContextMoveToPoint(context, imageSize.width, imageSize.height);
    CGContextAddLineToPoint(context, 0, imageSize.height / 2);
    CGContextMoveToPoint(context, 0, imageSize.height / 2); 
    CGContextAddLineToPoint(context, imageSize.width, 0);
//    CGContextFillPath(context);
  //  CGContextClosePath(context);

    // stroke and fill?
    CGContextDrawPath(context, kCGPathFillStroke);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIGraphicsPopContext();

    return image;    
}

感谢任何帮助。

【问题讨论】:

  • 我只是将 UIGraphicsBeginImageContextWithOptions 的第二个参数设置为 YES 以使其不透明思考 YUREKA!但是很可惜,这不起作用。

标签: cgcontext fill


【解决方案1】:

我从以下帖子中找到了答案: CGContext line drawing: CGContextFillPath not working?

最后一个答案提供了一个使用 CGMutablePathRef 的示例。对于三角形,我使用了以下代码:

CGMutablePathRef pathRef = CGPathCreateMutable();

CGPathMoveToPoint(pathRef, NULL, imageSize.width, 0);
CGPathAddLineToPoint(pathRef, NULL, imageSize.width, imageSize.height);
CGPathAddLineToPoint(pathRef, NULL, 0, imageSize.height / 2);
CGPathAddLineToPoint(pathRef, NULL, imageSize.width, 0);

CGPathCloseSubpath(pathRef);

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

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

CGPathRelease(pathRef);    

我不知道为什么我上面使用的原始方法不起作用。接下来我会弄清楚的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-11
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多