SwiftSwiftUIApple
Last updated at 2023-07-02

How to Clip Image in SwiftUI

ClickUp
Note
AI Status
Last Edit By
Last edited time
Jul 2, 2023 06:36 AM
Metatag
Slug
how-to-clip-image-in-swiftui
Writer
Published
Published
Date
Jun 26, 2023
Category
Swift
SwiftUI
Apple
In digital images, clipping is a technique that removes specific areas of the target image that exceed its bounds. Clipping has many advantages, such as making the image fit into its container, implementing corner radius on an image, and overlaying an image with a custom Shape.
Also Read:
The below image is quite big for a smartphone screen. We want to clip it to show the tree at the center of the image.
🚦
With Network Spy you can monitor, inspect, and modify your network traffic during development. Perfect for debugging and more analysis. πŸ™Œ Join the Waitlist Today! https://mozzlog.com/projects/network-spy

Standard Image Clipping

To perform image clipping, all you need to do is use .clipped modifier from the target view.
Image("tree") .resizable() .aspectRatio(contentMode: .fill) .frame(width: 350, height: 350) .clipped()
When you clip the above image, it will fit the image frame size.
For example, if the image is 2000β€ŠΓ—β€Š1333 while your view is a rectangle of 250x250, then using .clipped modifier will cut the remaining area of the image so the user cannot see it.

Corner Radius Image Clipping

When you use the Material Design library, you usually use cards to show a topic to the user. A Material card is usually a rectangle with a corner radius. We don’t want our image to exceed the card's bounds. Also, we don’t want the sharp corner of the image shown to the user. Hence, we should clip it.
Image("tree") .resizable() .aspectRatio(contentMode: .fill) .frame(width: 250, height: 250) .cornerRadius(30) .clipped()
Read More:

Custom Shape Image Clipping

Another common image clipping usage is to implement custom shapes.
Let’s imagine a situation when we implement a Podcast app that show most favorite podcast poster inside a star shape. That is where clipping can be useful to implement that.
To clip an image with a Shape you use .clipShape modifier.
Image("tree") .resizable() .aspectRatio(contentMode: .fill) .frame(width: 250, height: 250) .clipShape(Star(corners: 5, smoothness: 0.45))

Conclusion

Image clipping gives Swift developers a powerful tool to remove exceeding image automatically inside a view. This tool when combined with another one will result in a beautiful outcome for the UI.
Happy Clipping!
🚦
With Network Spy you can monitor, inspect, and modify your network traffic during development. Perfect for debugging and more analysis. πŸ™Œ Join the Waitlist Today! https://mozzlog.com/projects/network-spy
Β 

Discussion (0)

Related Posts