trim

Trims this shape by a fractional amount based on its representation as a path.

Shape ModifieriOS 13.0+macOS 10.15+tvOS 13.0+watchOS 6.0+trim(from:to:) in SwiftUI

Declaration

React
compose().trim({
  from?: number,
  to?: number,
})
Swift
nonisolated func trim(
    from startFraction: CGFloat = 0,
    to endFraction: CGFloat = 1
) -> some Shape

Parameters

  • options.fromnumber
  • options.tonumber

Return value

A shape built by capturing a portion of this shape's path.

Discussion

To create a Shape instance, you define the shape's path using lines and curves. Use the trim(from:to:) method to draw a portion of a shape by ignoring portions of the beginning and ending of the shape's path.

For example, if you're drawing a figure eight or infinity symbol (∞) starting from its center, setting the startFraction and endFraction to different values determines the parts of the overall shape.

The following example shows a simplified infinity symbol that draws only three quarters of the full shape. That is, of the two lobes of the symbol, one lobe is complete and the other is half complete.

Path { path in
    path.addLines([
        .init(x: 2, y: 1),
        .init(x: 1, y: 0),
        .init(x: 0, y: 1),
        .init(x: 1, y: 2),
        .init(x: 3, y: 0),
        .init(x: 4, y: 1),
        .init(x: 3, y: 2),
        .init(x: 2, y: 1)
    ])
}
.trim(from: 0.25, to: 1.0)
.scale(50, anchor: .topLeading)
.stroke(Color.black, lineWidth: 3)

Changing the parameters of trim(from:to:) to .trim(from: 0, to: 1) draws the full infinity symbol, while .trim(from: 0, to: 0.5) draws only the left lobe of the symbol.

See also

More in Shape modifiers.