Shapes vs Stacks
2023-10-22 本文已影响0人
_浅墨_
Shapes vs Stacks
与 Stacks 不同,Shapes占据最大空间。要为它们着色,需要使用fill
和foregroundColor
而不是background
。它们非常适合剪切内容和设置边框样式。
圆形
圆形允许绘制一个完美的圆形形状。圆形的直径等于宽度和高度中较小的那个数。
Circle()
.stroke(Color.black, lineWidth: 2)
.frame(width: 44, height: 44)
椭圆
椭圆类似于圆形,但不具有完美的1:1纵横比。当宽度和高度不同时,它将填充空间并自行变形。
Ellipse()
.stroke(Color.black, lineWidth: 2)
.frame(width: 44, height: 88)
矩形
尽管SwiftUI中的大多数元素(如堆叠、颜色和渐变)起初都是矩形,但它们不是形状。矩形具有一个shape
属性,允许它具有描边或用作蒙版。
Rectangle()
.foregroundColor(.blue)
.ignoresSafeArea()
圆角矩形
圆角矩形具有有用的cornerRadius
和style
属性。它非常适合创建按钮和生成 iOS 的平滑角。
RoundedRectangle(cornerRadius: 30, style: .continuous)
.fill(Color.green)
.frame(height: 44)
.overlay(Text("Sign up").bold())
** Capsule 形状**
类似于圆角矩形,Capsule 形状是药丸形状的。Capsule 的每一端都由一个半圆形成。我们可以用它们来制作按钮。
Capsule()
.fill(Color.green)
.frame(height: 44)
.overlay(Text("Sign up").bold())
接下来看一个示例:
ZStack {
Rectangle()
.fill(Color.blue).ignoresSafeArea()
VStack {
Circle()
.stroke(Color.black, lineWidth: 2)
.frame(width: 44, height: 44)
Text("Meng To").bold()
Capsule()
.foregroundColor(Color.green)
.frame(height: 44)
.overlay(Text("Sign up"))
}
.padding()
.background(Color.white)
.clipShape(RoundedRectangle(cornerRadius: 25.0, style: .continuous))
.padding()
}
![](https://img.haomeiwen.com/i130752/efee87504e865e49.jpg)