Today I will show you how to use Capsule.
I will use multiple Capsules to draw a colored petal.
Steps:
First, add a Capsule. Its default fill color is black.
Set the Capsule's inset to 20.
Capsule()
.inset(by: 20)
Draw a new Capsule and set its RoundedCornerStyle to circular.
Capsule(style: .circular)
Change the RoundedCornerStyle of Capsule to continuous.
Capsule(style: .continuous)
Define a custom Capsule struct.
Add two properties to the struct as the Capsule's fill color and rotation angle.
Then, implement the body property in the protocol to draw a custom view.
Draw a basic Capsule first.
struct MyCapsule: View {
var color: Color
var degree: Double
var body: some View {
Capsule()
}
}
Modify the view in PreviewProvider to a custom view.
Set the Capsule's fill color to the value of the color property.
struct MyCapsule: View {
var color: Color
var degree: Double
var body: some View {
Capsule()
.foregroundColor(color)
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
MyCapsule(color: .blue, degree: 0)
}
}
#endif
Set the Capsule's width to 60 and height to 90.
Then offset the Capsule downward by a distance of 60 points.
Then apply the rotation effect to the Capsule. The rotation angle is the value of the degree property.
Finally, set the opacity of the Capsule to 0.8 so that when multiple Capsules are superimposed, you can see the color of the Capsules below.
Capsule()
.foregroundColor(color)
.frame(width: 60, height: 90)
.offset(x: 0, y: 60)
.rotationEffect(.degrees(degree))
.opacity(0.8)
Revert the view in the PreviewProvider to display the content in the ContentView.
Add a ZStack as a container for subviews.
Draw two custom Capsules. Use blue as the fill color; the rotation angles are 0 and 45 degrees, respectively.
Continue to draw two custom Capsules. Use yellow as the fill color; the rotation angles are 90 and 135 degrees, respectively.
Continue to draw two custom Capsules. Use red as the fill color; the rotation angles are 180 and 225 degrees, respectively.
Draw the last two custom Capsules. Again, use green as the fill color; the rotation angles are 270 and 315 degrees, respectively.
In this way, we have completed the drawing of a petal.
import SwiftUI
struct ContentView: View {
var body: some View {
ZStack {
MyCapsule(color: .blue, degree: 0)
MyCapsule(color: .blue, degree: 45)
MyCapsule(color: .yellow, degree: 90)
MyCapsule(color: .yellow, degree: 135)
MyCapsule(color: .red, degree: 180)
MyCapsule(color: .red, degree: 225)
MyCapsule(color: .green, degree: 270)
MyCapsule(color: .green, degree: 315)
}
}
}
struct MyCapsule: View {
var color: Color
var degree: Double
var body: some View {
Capsule()
.foregroundColor(color)
.frame(width: 60, height: 90)
.offset(x: 0, y: 60)
.rotationEffect(.degrees(degree))
.opacity(0.8)
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif
Follow me on:
Comments