2012-06-23 88 views
0

以下方法應該創建一個FILLED三角形圖像,但它只創建一個輪廓。 爲什麼不填充?與這一個去瘋狂。我希望它得到迴應,以便下一個可憐的靈魂在這個問題上掙扎,可以消除這個障礙並挽救他們一個小時的生命。無法爲簡單形狀填充CGContext

這裏是我寫的方法:

+ (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;  
} 

任何幫助表示讚賞。

+0

我只是將UIGraphicsBeginImageContextWithOptions的第二個參數設置爲YES,以使其不透明思考YUREKA!但是,唉,這不起作用。 – Christopher

回答

2

我發現從以下職位的答案: 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);  

我不知道爲什麼,我在上面使用的原始方法不但是工作。接下來我會弄清楚。