Skip to main content

How to combine shapes to create new shapes

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to combine shapes to create new shapes 관련

SwiftUI by Example

Back to Home

How to combine shapes to create new shapes | SwiftUI by Example

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)

Download this as an Xcode projectopen in new window

A circle and capsule shape combined together, then filled as one.
A circle and capsule shape combined together, then filled as one.

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()

Download this as an Xcode projectopen in new window

A circle shape where four corners have been cut out.
A circle shape where four corners have been cut out.

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()

Download this as an Xcode projectopen in new window

Two overlapping circles, where the intersection area is hollow.
Two overlapping circles, where the intersection area is hollow.
Similar solutions…
How to combine text views together | SwiftUI by Example

How to combine text views together
How to combine transitions | SwiftUI by Example

How to combine transitions
SwiftUI's built-in shapes | SwiftUI by Example

SwiftUI's built-in shapes
How to fill and stroke shapes at the same time | SwiftUI by Example

How to fill and stroke shapes at the same time
How to display solid shapes | SwiftUI by Example

How to display solid shapes

이찬희 (MarkiiimarK)
Never Stop Learning.