跳转至
Structure

Rectangle

A rectangle shape.

Declaration

@frozen struct Rectangle : Shape

Overview

A Rectangle is a four-sided Shape with 90 degree angle corners that automatically aligns itself inside of the view containing it. By default, a Rectangle has black fill and takes up the space of it's container:

struct ContentView: View {
    var body: some View {
        Rectangle()
    }
}
A default rectangle filling the screen.

To define a Rectangle with a specific color and frame, use the fill(_:style:) and frame(width:height:alignment:) modifiers:

struct ExampleView: View {
    var body: some View {
        Rectangle()
            .fill(Color.blue)
            .frame(width: 250, height: 150)
    }
}
A screenshot displaying a filled blue rectangle at the center of the screen which renders with width of 250 and height of 150 given the frame applied.

To add a border, use the stroke(_:lineWidth:) modifier, and use the inset(by:) modifier to inset the rectangle by half of the border width to keep the rectangle at its original size:

struct ExampleView: View {
    var body: some View {
        Rectangle()
            .inset(by: 10)
            .stroke(Color.blue, lineWidth: 20)
            .frame(width: 250, height: 150)
    }
}
A screenshot displaying a rectangle which renders as a blue rectangular border by applying an inset to the original rectangle and increasing the lineWidth of the stroke to keep it at its original size.

Availability

iOS 13.0+

macOS 10.15+

tvOS 13.0+

watchOS 6.0+

Topics


Type Alias

AnimatableData The type defining the data to animate.

Body The type of view representing the body of this view.

InsetShape The type of the inset shape.


Initializer

init() Creates a Rectangle that aligns itself inside of the view containing it by default.


Instance Method

inset(by:) Returns a Rectangle insetted by the amount specified.

path(in:) Used to describe a Rectangle as a path in a CGRect.