Introduction to SwiftUI with Rounded Corners
In this article, we will explore the world of SwiftUI and learn how to add borders with rounded corners to an image. We will dive into the details of using clipShape and overlay modifiers in SwiftUI.
What is SwiftUI?
SwiftUI is a powerful framework for building iOS, iPadOS, macOS, watchOS, and tvOS apps in Swift. It was introduced in Xcode 11 and provides a declarative way to build user interfaces.
What are Rounded Corners in SwiftUI?
Rounded corners in SwiftUI refer to the curved edges of a view. They can be used to create visually appealing borders around images or other views.
Beta 4 Deprecation Warning
In beta 4, you might have encountered a deprecation warning related to using cornerRadius with an Image. The warning suggests using a RoundedRectangleShape instead. This is because cornerRadius was not designed for use with images.
How to Fix the Deprecation Warning
To fix the deprecation warning, you need to replace cornerRadius with a clipShape modifier and then overlay a stroke on top of it. This approach provides more control over the border and its appearance.
Using clipShape & overlay Modifiers
In this section, we will explore how to use the clipShape and overlay modifiers in SwiftUI to add borders with rounded corners to an image.
Example Code
VStack(spacing: 40) {
Text("Image Border").font(.largeTitle)
Text("Using cornerRadius & overlay").font(.title).foregroundColor(.gray)
Text("Using cornerRadius will also clip the image. Then overlay a border.")
.frame(maxWidth: .infinity)
.font(.title)
.padding()
.background(Color.orange)
.foregroundColor(.black)
Image("profile")
.clipShape(.rect(cornerRadius: 10))
.overlay(.rect(cornerRadius: 10)
.stroke(Color.orange, lineWidth: 4))
.shadow(radius: 10)
}
How it Works
In the example code above:
- We define a
VStackwith a spacing of 40 points. - We add two
Textviews with different fonts and colors to the stack. - We add an image to the stack using the
Imageview. - We use the
clipShape(.rect(cornerRadius: 10))modifier on the image to clip it to a rectangle with a corner radius of 10 points. - We overlay a stroke on top of the clipped image using the
.overlay(.rect(cornerRadius: 10).stroke(Color.orange, lineWidth: 4))modifier. - Finally, we add a shadow to the view using the
.shadow(radius: 10)modifier.
Result
The resulting view has a rounded border around the image with a corner radius of 10 points.
Conclusion
In this article, we learned how to add borders with rounded corners to an image in SwiftUI by using the clipShape and overlay modifiers. We explored the deprecation warning related to cornerRadius and provided a solution that works around it.
Last modified on 2023-05-18