0

I want to invert the CGContextClip() so with this code:

    let startPoint: CGFloat = CGFloat(degreesToRadians(270))
    let endPoint: CGFloat = CGFloat(degreesToRadians(0))

    var path: CGMutablePathRef = CGPathCreateMutable()
    CGPathAddArc(path, nil, CGFloat(self.frame.size.width / 2.0), CGFloat(self.frame.size.height / 2.0), 155, startPoint, endPoint, false)
    CGPathAddArc(path, nil, CGFloat(self.frame.size.width / 2.0), CGFloat(self.frame.size.height / 2.0), 84, endPoint, startPoint, true)
    CGContextAddPath(ctx, path)

    CGContextDrawImage(ctx, CGPathGetBoundingBox(path), image.CGImage)
    CGContextFillPath(ctx)
    CGContextClosePath(ctx)
    CGContextClip(ctx)

I'm getting this : enter image description here

Is it posible to invert clipping area to get image inside my line?

2 Answers2

3

This code isn't clipping anything

It's just filling your path with black. You need to call CGContextClip before you draw your image. That in itself should achieve your desired effect (having the image masked within the arc area).

Also, CGContextClosePath should be called before adding your path to the context. And if you're just masking, you shouldn't need to call CGContextFillPath.

Something like this should achieve what you want:

let startPoint = -CGFloat(M_PI)*0.5
let endPoint = CGFloat(0)

let ctx = UIGraphicsGetCurrentContext()

let path = CGPathCreateMutable()
CGPathAddArc(path, nil, frame.size.width / 2.0, frame.size.height / 2.0, 155, startPoint, endPoint, false)
CGPathAddArc(path, nil, frame.size.width / 2.0, frame.size.height / 2.0, 84, endPoint, startPoint, true)
CGContextClosePath(ctx)
CGContextAddPath(ctx, path)
CGContextClip(ctx)

CGContextDrawImage(ctx, CGPathGetBoundingBox(path), image.CGImage)

enter image description here

If you still need the inverse, Matt's answer has got you covered.


Side Node

You (most of the time) don't need to explicitly supply type information when defining a variable. Let Swift infer it. Therefore, you can replace lines like this:

var path: CGMutablePathRef = CGPathCreateMutable()

with this:

var path = CGPathCreateMutable()
Community
  • 1
  • 1
Hamish
  • 78,605
  • 19
  • 187
  • 280
1

You can use specify a different fill mode (even-odd) and use an outer path along with your main (inner) path which should give you what you're looking for. Here's some additional details that might help: Drawing Hollow circle in iPhone

Community
  • 1
  • 1
Matt Long
  • 24,438
  • 4
  • 73
  • 99