DEV Community

GoyesDev
GoyesDev

Posted on

[SUI] Formas personalizadas

Shape permite construir una forma dentro de un CGRect usando Path.

  • path(in:). Recibe las dimensiones de la vista.
struct Polygon: Shape {
  var corners: [UnitPoint]

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

    let actualCorners = corners.map { normalizedCorner in
      CGPoint(x: rect.origin.x + normalizedCorner.x * rect.width, y: rect.origin.y + normalizedCorner.y * rect.height)
    }

    actualCorners.enumerated().forEach { (index, corner) in
      if index == 0 {
        path.move(to: corner )
      } else {
        path.addLine(to: corner )
      }
    }

    path.closeSubpath()

    return path
  }
}
Enter fullscreen mode Exit fullscreen mode
#Preview {
  VStack {
    Polygon(corners: [
      .init(x: 0, y: 0),
      .init(x: 1, y: 0),
      .init(x: 1, y: 1),
      .init(x: 0, y: 0.5),
    ])
    .fill(.red)
    .frame(width: 100, height: 100)
    .padding()

    Polygon(corners: [
      .init(x: 0, y: 0),
      .init(x: 1, y: 0),
      .init(x: 1, y: 1),
      .init(x: 0, y: 0.5),
    ])
    .fill(.blue)
    .frame(width: 200, height: 200)
    .padding()
  }
}
Enter fullscreen mode Exit fullscreen mode


Bibliografía

Top comments (0)