Skip to main content

How to clip a view so only part is visible

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to clip a view so only part is visible 관련

SwiftUI by Example

Back to Home

How to clip a view so only part is visible | SwiftUI by Example

How to clip a view so only part is visible

Updated for Xcode 15

SwiftUI lets you clip any view to control its shape, all by using the clipShape() modifier.

For example this creates a button using the system image “bolt.fill” (a filled lightning bolt), gives it some padding and a background color, then clips it using a circle so that we get a circular button:

Button {
    print("Button was pressed!")
} label: {
    Image(systemName: "bolt.fill")
        .foregroundStyle(.white)
        .padding()
        .background(.green)
        .clipShape(Circle())
}

Download this as an Xcode projectopen in new window

A white lightning bolt icon inside a green circle.
A white lightning bolt icon inside a green circle.

The Circle clip shape will always make circles from views, even if their width and height are unequal – it will just crop the larger value to match the small.

As well as Circle there’s also Capsule, which crops a view to have rounded corners in a lozenge shape. For example, this creates the same button using a capsule shape:

Button {
    print("Pressed!")
} label: {
    Image(systemName: "bolt.fill")
        .foregroundStyle(.white)
        .padding(EdgeInsets(top: 10, leading: 20, bottom: 10, trailing: 20))
        .background(.green)
        .clipShape(Capsule())
}

Download this as an Xcode projectopen in new window

A white lightning bolt icon inside a green capsule or pill shape.
A white lightning bolt icon inside a green capsule or pill shape.

I added some more precise padding there to get a better shape – you should experiment to find something you like.

Similar solutions…
How to draw part of a solid shape using trim() | SwiftUI by Example

How to draw part of a solid shape using trim()
How to fix “Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements” | SwiftUI by Example

How to fix “Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements”
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks
How to convert a SwiftUI view to an image | SwiftUI by Example

How to convert a SwiftUI view to an image
How to make a view dismiss itself | SwiftUI by Example

How to make a view dismiss itself

이찬희 (MarkiiimarK)
Never Stop Learning.