[SU] Shapes
Source: Dev.to
Consideraciones
Una forma asume el tamaño del frame que la contiene.
Rectangle.init()RoundedRectangle.init(cornerRadius:style:)Circle.init()Ellipse.init()Capsule.init(style:)
Inicializadores de Shape
Rectangle()
RoundedRectangle(cornerRadius: 20, style: .continuous)
Circle()
Ellipse()
Capsule()
Ejemplo de Shapes
struct ContentView: View {
var body: some View {
HStack {
Rectangle()
.frame(width: 100, height: 120)
RoundedRectangle(cornerRadius: 20, style: .continuous)
.frame(width: 100, height: 120)
Circle()
.frame(width: 100, height: 120)
Ellipse()
.frame(width: 100, height: 120)
Capsule()
.frame(width: 100, height: 120)
}
.padding()
}
}
Métodos de Shape
Shape.fill(_:style:): rellena la forma con un color o gradiente.ShapeView.stroke(_:lineWidth:antialiased:): dibuja el borde de la forma usando un color o gradiente. El borde se expande 50 % hacia afuera y 50 % hacia dentro.ShapeView.stroke(_:style:antialiased:): dibuja el borde con información adicional de estilo medianteStrokeStyle.ShapeView.strokeBorder(_:style:antialiased:): devuelve una vista que aplica un margen interior equivalente a la mitad del grosor de línea; el borde se expande 100 % hacia dentro.ShapeView.strokeBorder(_:lineWidth:antialiased:): variante que solo especifica el ancho de línea.
Ejemplo de relleno y borde
struct ContentView: View {
var body: some View {
HStack {
Rectangle()
.fill(.red)
.frame(width: 100, height: 120)
RoundedRectangle(cornerRadius: 20, style: .continuous)
.fill(.white)
.stroke(.red, lineWidth: 2)
.frame(width: 100, height: 120)
Circle()
.fill(Color.white)
.stroke(.red,
style: .init(lineWidth: 4,
lineCap: .round,
lineJoin: .miter,
miterLimit: 0,
dash: [10, 10],
dashPhase: 10))
.frame(width: 100, height: 120)
Ellipse()
.fill(Color.white)
.strokeBorder(.red,
style: .init(lineWidth: 4,
lineCap: .round,
lineJoin: .miter,
miterLimit: 0,
dash: [10, 10],
dashPhase: 10))
.frame(width: 100, height: 120)
Capsule()
.fill(Color.white)
.strokeBorder(.red,
style: .init(lineWidth: 4,
lineCap: .round,
lineJoin: .miter,
miterLimit: 0,
dash: [10, 10],
dashPhase: 10))
.frame(width: 100, height: 120)
}
.padding()
}
}
Uso de Shape como fondo de una vista
struct ContentView: View {
var body: some View {
VStack {
Button {
debugPrint("Hola1")
} label: {
Text("Activar 1")
.padding()
}
.tint(.white)
.background(
Capsule()
.fill(Color.blue)
)
Button {
debugPrint("Hola2")
} label: {
Text("Activar 2")
.padding()
}
.tint(.white)
.background(.blue, in: Capsule())
}
.padding()
}
}
Referencias
Gauchat, J. D. (2024). SwiftUI for Masterminds: How to take advantage of Swift and SwiftUI to create insanely great apps for iPhones, iPads, and Macs (5ª ed.). John D Gauchat.