Search code examples
iosswiftcgcontextuigraphicscontext

CGContextSetLineCap/CGContextSetLineJoin ignored when creating ImageContext


For some reason, when trying to create a line with round corners, all the others properties are applied beside this two

 UIGraphicsBeginImageContextWithOptions(size, opaque, scale)
        let context = UIGraphicsGetCurrentContext()
            CGContextSetStrokeColorWithColor(context, color.CGColor)
            CGContextSetLineCap(context, CGLineCap.Round) //Ignored
            CGContextSetLineJoin(context, CGLineJoin.Round) //Ignored
            CGContextSetLineWidth(context, lineWidth)
        CGContextSaveGState(context)

        CGContextMoveToPoint(context, bounds.midX, 0)
        CGContextAddLineToPoint(context, bounds.midX, bounds.maxY)
        CGContextRestoreGState(context)
        CGContextStrokePath(context)

         // Drawing complete, retrieve the finished image and cleanup
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

Result:

enter image description here

Any suggestions? Thanks!


Solution

  • Line caps are added beyond the endpoints of a path. Your path extends over the full range of y-coordinates of the bounds, therefore the line caps are outside of the bounds.