RoundedRectangle
是 SwiftUI 中的一个内置形状(Shape),用于绘制带有圆角的矩形。它非常适合用来创建带有圆角的 UI 元素,比如按钮、卡片、背景框等。
RoundedRectangle
的基本用法
#
1. 创建一个简单的圆角矩形 #
import SwiftUI
struct ContentView: View {
var body: some View {
RoundedRectangle(cornerRadius: 20)
.fill(Color.blue) // 填充颜色
.frame(width: 200, height: 100) // 设置尺寸
}
}
cornerRadius: 20
: 设置圆角的半径为 20。.fill(Color.blue)
: 填充蓝色。.frame(width: 200, height: 100)
: 设置矩形的宽度和高度。
运行结果:
一个宽度为 200,高度为 100,圆角半径为 20 的蓝色矩形。
2. 设置不同的圆角半径 #
RoundedRectangle
还支持为每个角设置不同的圆角半径。例如:
RoundedRectangle(cornerSize: CGSize(width: 20, height: 10)) // 设置圆角的宽度和高度
.fill(Color.green)
.frame(width: 200, height: 100)
cornerSize: CGSize(width: 20, height: 10)
: 设置圆角的宽度为 20,高度为 10。
3. 添加边框 #
你可以使用 stroke
方法为 RoundedRectangle
添加边框:
RoundedRectangle(cornerRadius: 20)
.stroke(Color.red, lineWidth: 3) // 添加红色边框,宽度为 3
.frame(width: 200, height: 100)
stroke(Color.red, lineWidth: 3)
: 添加红色边框,宽度为 3。
4. 结合 overlay
使用
#
RoundedRectangle
常用于 overlay
中,为其他视图添加圆角边框。例如:
Text("Hello, SwiftUI!")
.padding()
.background(Color.yellow)
.cornerRadius(10)
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.orange, lineWidth: 2) // 添加橙色边框
)
运行结果:
一个带有圆角背景和橙色边框的文本视图。
5. 自定义圆角 #
你可以通过 RoundedRectangle(cornerRadius:style:)
或 RoundedRectangle(cornerSize:style:)
来进一步自定义圆角的样式。例如:
RoundedRectangle(cornerRadius: 20, style: .continuous) // 使用连续的圆角样式
.fill(Color.purple)
.frame(width: 200, height: 100)
style: .continuous
: 使用连续的圆角样式,使圆角更加平滑。
RoundedRectangle
的核心参数
#
参数 | 描述 |
---|---|
cornerRadius: CGFloat | 设置所有圆角的半径。 |
cornerSize: CGSize | 设置圆角的宽度和高度(可以分别控制水平和垂直方向的圆角大小)。 |
style: RoundedCornerStyle | 设置圆角的样式,默认为 .circular ,可选 .continuous 使圆角更平滑。 |
RoundedRectangle
的常见用途
#
按钮背景
Button(action: {}) { Text("Click Me") .padding() .background( RoundedRectangle(cornerRadius: 10) .fill(Color.blue) ) }
卡片视图
VStack { Text("Card Title") .font(.title) Text("This is a card with rounded corners.") .font(.body) } .padding() .background( RoundedRectangle(cornerRadius: 15) .fill(Color.white) .shadow(radius: 5) )
进度条背景
ZStack(alignment: .leading) { RoundedRectangle(cornerRadius: 10) .fill(Color.gray.opacity(0.3)) .frame(height: 20) RoundedRectangle(cornerRadius: 10) .fill(Color.blue) .frame(width: 100, height: 20) // 模拟进度 }
总结 #
RoundedRectangle
是 SwiftUI 中用于绘制圆角矩形的强大工具。它的主要特点包括:
- 支持设置统一的圆角半径或分别控制每个角的半径。
- 可以通过
fill
填充颜色,或通过stroke
添加边框。 - 常用于创建按钮、卡片、背景框等 UI 元素。
通过灵活使用 RoundedRectangle
,你可以轻松实现各种美观的圆角设计。