Search code examples
core-graphicsobjective-c++

Why isn't my path closing in core graphics?


This is my code for drawing a polygon. It works but doesn't close or fill.

CGContextBeginPath(DrawContext);
for(int i=0;i<sides-1;i++) {
  CGContextMoveToPoint(DrawContext, getRealPos(i)->getX(), getRealPos(i)->getY());
  CGContextAddLineToPoint(DrawContext, getRealPos(i+1)->getX(), getRealPos(i+1)->getY());
}
CGContextClosePath(DrawContext);
CGContextStrokePath(DrawContext);
CGContextFillPath(DrawContext);

Solution

  • You are facing this problem because you are using CGContextMoveToPoint in loop. CGContextMoveToPoint is used to set the current point and start a new sub path. In other words, just to define a starting point of a path.

    And CGContextAddLineToPoint will add the line from this point to the specified point and also sets the current point to the endpoint of the line segment. So you don't have to use CGContextMoveToPoint every time after drawing one line. Moreover, when you use CGContextMoveToPoint, it starts altogether a new sub path. So basically you are closing only one sub path in your code and thats the last one.

    So use CGContextMoveToPoint only once outside the for loop and then continue drawing using CGContextAddLineToPoint. And at last close it using CGContextClosePath.

    For further understanding refer docs:

    https://developer.apple.com/library/ios/documentation/graphicsimaging/reference/CGContext/Reference/reference.html#//apple_ref/c/func/CGContextMoveToPoint