top of page
Writer's pictureHui Wang

42. SwiftUI: Introducing Rectangle and RoundedRectangle

Today I will show you how to use Rectangle and RoundedRectangle.


Steps:

  • First, draw a simple Rectangle with a default fill color of black.

Rectangle()

  • Change its color to yellow and set its width and height.

Rectangle()
    .fill(.yellow)
    .frame(width: 200, height: 200)

  • Then, create a set of overlapping rectangles.

  • Add a ZStack as a container for the subviews.

  • Draw a rectangle and set its fill color to blue.

  • Set its width and height.

ZStack {
    Rectangle()
        .fill(.blue)
        .frame(width: 300, height: 300)
}

  • Then draw a second yellow rectangle and make it 0.8 times smaller.

  • Finally, in the same way, draw a third red rectangle and make it 0.6 times smaller.

  • This way, we have completed the drawing of the three overlapping rectangles.

ZStack {
    Rectangle()
        .fill(.blue)
        .frame(width: 300, height: 300)

    Rectangle()
        .fill(.yellow)
        .frame(width: 300, height: 300)
        .scaleEffect(0.8)

    Rectangle()
        .fill(.red)
        .frame(width: 300, height: 300)
        .scaleEffect(0.6)
}

  • Next, draw a RoundedRectangle and set its corner radius to 120.

  • Sets the rounded corners' width and height.

RoundedRectangle(cornerSize: CGSize(width: 60, height: 60))
    .frame(width: 300, height: 200)

  • Draw a RoundedRectangle with a corner radius of 60.

  • Set the rounded corner style to .continuous, which means rounded corners with continuous curvature.

RoundedRectangle(cornerRadius: 60, style: .continuous)

  • Add a stroke to the RoundedRectangle and set the stroke width to 20.

RoundedRectangle(cornerRadius: 60, style: .continuous)
    .stroke(lineWidth: 20)

Source and final effect:

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        VStack {
            Rectangle()
                .fill(.yellow)
                .frame(width: 100, height: 100)
            
            ZStack {
                Rectangle()
                    .fill(.blue)
                    .frame(width: 150, height: 150)
                
                Rectangle()
                    .fill(.yellow)
                    .frame(width: 150, height: 150)
                    .scaleEffect(0.8)
                
                Rectangle()
                    .fill(.red)
                    .frame(width: 150, height: 150)
                    .scaleEffect(0.6)
            }
            
            RoundedRectangle(cornerSize: CGSize(width: 30, height: 30))
                .frame(width: 150, height: 100)
            
            RoundedRectangle(cornerRadius: 30, style: .continuous)
                .stroke(lineWidth: 20)
                .padding()
        }
        .padding()
    }
}

 

Follow me on:

Comments


bottom of page