CGRect
has a very convenient built-in constant: CGRect.null
let aRect = ... //get rect from somewhere
CGRect.null.union(aRect) //is aRect
CGRect.null.intersection(aRect) //is CGRect.null
CGPath
doesn’t have anything like this, meaning you can’t do something like:
let bunchOfPaths = [...] //array of CGPaths
let unionPath = bunchOfPaths.reduce(CGPath.null, { $0.union($1) }) //union of all the paths
Nor can you use CGRect.null
to create the equivalent:
let nullRectPath = CGPath(rect: .null, transform: nil)
nullRectPath.isEmpty //false (?!)
let zeroRectPath = CGPath(rect: .zero, transform: nil)
nullRectPath.union(zeroRectPath) == zeroRectPath //false
Creating an empty path isn’t helpful either:
let emptyPath = zeroRectPath.subtracting(zeroRectPath)
emptyPath.isEmpty //true
emptyPath.union(zeroRectPath) == zeroRectPath //false (!!)
Does a CGPath
with the properties described (its union with any CGPath
is the other path, its intersection with any CGPath
is itself) exist, and if so, how can it be created?
2
Answers
Instead of CGPath, use CGMutablePath:
The problem you’re facing is that CGPath’s
==
does not mean "contains the same points." It means "contains the same drawing instructions in the same order." Andunion(using:)
does not promise to preserve the order of the drawing instructions. It can’t, since it has a fill rule. It’s not just appending two paths; it’s merging them.You can see this by printing out the contents:
These are not "equal." The tool you want here is
.addPath
.Now this is a bit annoying for your use case, but you can clean it up: