SwiftUI - Shapes



Shapes are used to create graphic elements for the user interface in SwiftUI. They are re-sizable, customizable, and reusable. They can create complex and user-friendly designs very efficiently. SwiftUI provides various predefined shapes such as rectangles, circles, etc., and allows us to create any custom shape using the Shape protocol easily.

We can customize any shape with the help of predefined modifiers such as fill(), background(), etc. In this chapter, we are going to learn how to create shapes and learn about the predefined method, and modifiers, provided by SwiftUI.

Creating a Custom Shape in SwiftUI

In SwiftUI, we can create shapes either using pre-defined methods or using Shape protocol. Here the Shape protocol is used to create custom shapes. So to create a custom shape we need to create a structure that conforms to the Shape protocol.

In this structure, we call the path(in:) method to define the path of the shape with the help of the Path struct. After that, we use this structure in the ContentView to customize the shape and get the live preview of the shape. We can also create shapes simply by using the Path() structure.

Example 1

The following SwiftUI program is used to create a custom square shape using Shape protocol.

import SwiftUI

struct mySquare: Shape {
   func path(in rect: CGRect) -> Path {
      var path = Path()

      path.move(to: CGPoint(x: rect.minX, y: rect.minY))
      path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
      path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
      path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
      path.closeSubpath()
      return path
   }
}

struct ContentView: View {
   var body: some View {
      mySquare()
         .fill(Color.green)
         .frame(width: 100, height: 100)
   }
}

#Preview {
   ContentView()
}

Output

Shapes

Example 2

The following SwiftUI program is used to create a custom square shape using Path() structure.

import SwiftUI

struct ContentView: View {
  var body: some View {
    Path { xPath in
      xPath.move(to: CGPoint(x: 50, y: 50))
      xPath.addLine(to: CGPoint(x: 110, y: 50))
      xPath.addLine(to: CGPoint(x: 110, y: 100))
      xPath.addLine(to: CGPoint(x: 50, y: 100))
      xPath.closeSubpath()
    }
    .stroke(Color.red, lineWidth: 5)
  }
}

#Preview {
  ContentView()
}

Output

Shapes

Methods Used to Create Shapes in SwiftUI

SwiftUI supports various in-built methods that are used in developing various types of shapes which makes the UI more attractive. Some of the commonly used methods are as follows−

Method Description
path(in rect:CGRect)->Path This method is used to specify the shape outline in a rectangular frame of reference. It takes only one rect parameter, it represents the frame of reference that is specified for the given shape.
move(to end:CGPoint) It is used to specify the point from where the new path will start. This method takes only one parameter which is the end. Here end contains the starting coordinates of the new subpath.
addLine(to end: CGPoint) This method is used to insert a straight line from the current point to the specified point. It takes only one parameter that is, end. This parameter represents the coordinates of the endpoint of the line segment.
addArc() This method is used to insert an arc of a circle of the given radius and angle in the path. This method takes six parameters:
  • center is used to represent the center coordinates.
  • radius is used to represent radius coordinates.
  • startAngle represents the angle to the starting point of the arc.
  • endAndle represents the angle to end point of the arc.
  • clockwise is used to specify the direction of the arc if it set to true then the arc is created in a clockwise direction, otherwise the arc will be created in an anticlockwise direction.
  • The transform parameter is used to apply an affine transform to the arc before adding it to the given path.
addCurve(to:control1:control2) This method is used to create a curve, the curve starts from the current point of the path and ends at the specified endpoint. The curvature of the curve is managed by the two control points.
addEllipse(in:transform:) This function is used to insert an ellipse in the rectangle. Here the center of the ellipse is the midpoint of the rectangle that is specified by the rect parameter and the major and minor axes of the ellipse are specified by the width and height of the rectangle.
addRect(CGRect, transform) This function is used to add a rectangle path in the given path.
closeSubpath() This method is used to close the current subpath.
forEach(Path.Element) This method is used to call the body with each element present in the given path.

Modifiers Used to Customize Shapes in SwiftUI

SwiftUI supports various in-built modifiers to modify the shape according to the requirement of the user interface's design. We can use single or multiple modifiers on a shape. SwiftUI executes modifiers sequentially so apply them accordingly. Some of the commonly used modifiers are−

Modifier Description
.fill() It is used to fill the shape with a color or gradient. For color you can use "Color.colorName" as a parameter or for gradient you can use ".colorName.gradient".
.stroke(_content:style:) It is used to create an outline of the shape with the help of color or gradient. It takes two parameters that are: content is the color or gradient with which to stroke the shape and style to enhance the stroke by adjusting the line's width and the type of lines such as a simple continuous line or dashed line.
.frame(width:height:alignment:) It is used to set the shape in the invisible frame where we can adjust the height, width and alignment of the shape according to our requirements.
.shadow(color:radius:x:y:) It is used to apply shadow effect on the given shape. This modifier takes four parameters and they are optional means you can use any of them or all of them its up to your requirement. Here the color parameter is used to specify the shadow's color, radius parameter specifies how much we can blur the shadow, x and y are the amount of offset the shadow horizontally and vertically.
.opacity(value) It is used to adjust the transparency of the given shape. Here the value of this modifier is vary in between 0(completely transparent) and 1(completely opaque)
.rotationEffect(_angle:anchor:) It is used to rotate the shape in the specific angle. This method takes two parameters: angle by which to rotate the image and anchor is the unit of point about which the shape perform rotation and the default value of this parameter is center.
.offset(x:,y:) It is used to move the shape by specific amount horizontally and vertically. It takes two parameters: x to offset the shape horizontally and y to offset the shape vertically.
.overlay It is used to add/overlay another view on top of the given shape.
.background It is used to add another view in the back side of the given shape.

Built-in Shapes in SwiftUI

SwiftUI provides some in-built shapes that are used to desgine various compoenents. These shapes are easy to use and easy to customize such as styling, coloring, padding, etc., with the help of modifiers provided by SwiftUI. Follow are the in-buil shapes supported by SwiftUI−

Shape Description
Circle() It is used to create a circular shape.
Ellipse() It is used to create ellipse type shape.
Rectangle() It is used to create a rectangular shape.
RoundedRectangle() It is used to created rounded rectangle shape.
Capsule() It is used to create a capsule or pill like shape.
Advertisements