How to combine shapes to create new shapes
How to combine shapes to create new shapes 관련
Updated for Xcode 15
New in iOS 17
All of SwiftUI's shapes can be combined in various ways to create new shapes, including union (a filled region merging both shapes), intersection (a filled region containing regions common in both shapes), line intersection (returns the line of one shape overlaps the fill of another), and more.
For example, this combines a circle with a capsule inset by 100 points, then fills the result blue:
Circle()
.union(.capsule.inset(by: 100))
.fill(.blue)
The advantage to having a single shape is that the result blends well when you add opacity – you're not rendering two overlapping shapes individually, but combining them both into a single shape and rendering that.
Similarly, we could use lineSubtraction()
to cut a rectangle's shape away from a circle, then stroke the remainder with a rounded cap:
Circle()
.lineSubtraction(.rect.inset(by: 30))
.stroke(style: .init(lineWidth: 20, lineCap: .round))
.padding()
Or we could place one circle off to the left, then subtract another circle offset to the right:
Circle()
.offset(x: -100)
.symmetricDifference(.circle.offset(x: 100))
.fill(.red)
.padding()