CGContextFillPath(context) gets removed when creating a line

206 views Asked by At

I use the below code for fill path in viewDidLoadit works perfect

UIGraphicsBeginImageContext(_drawingPad.frame.size);
CGContextRef context1 = UIGraphicsGetCurrentContext();

CGContextMoveToPoint(context1, 300, 300);
CGContextAddLineToPoint(context1, 400, 350);
CGContextAddLineToPoint(context1, 300, 400);
CGContextAddLineToPoint(context1, 250, 350);
CGContextAddLineToPoint(context1, 300, 300);

CGContextClosePath(context1);
//CGContextStrokePath(context1);

CGContextSetFillColorWithColor(context1, [UIColor redColor].CGColor);
CGContextFillPath(context1);
CGContextStrokePath(context1);

also I'm creating a line when touches begin.. but the fill path get erased before I create the line..

2

There are 2 answers

1
CodenameLambda1 On

You're trying to draw path without creating a path.

Try the following:

UIGraphicsBeginImageContext(_drawingPad.frame.size);
CGContextRef context1 = UIGraphicsGetCurrentContext();

CGMutablePathRef path = CGPathCreateMutable();

CGPathMoveToPoint(path,300,300);
CGPathAddLineToPoint(path,400,350);
CGPathAddLineToPoint(path,300,400);
CGPathAddLineToPoint(path,250,350);
CGPathAddLineToPoint(path,300,300);

CGPathCloseSubpath(path);

CGContextSetStrokeColorWithColor(context1, [UIColor blackColor].CGColor);
CGContextSetFillColorWithColor(context1, [UIColor redColor].CGColor);


CGContextAddPath(context1,path);

//Now you can fill and stroke the path
CGContextFillPath(context1);
CGContextStrokePath(context1);

CGPathRelease(path); //free up memory
1
Martin R On

Replace

CGContextFillPath(context1);
CGContextStrokePath(context1);

by

CGContextDrawPath(context1, kCGPathFillStroke);

That will fill and stroke the current path without erasing it in between.