由于 API 变动,此文章部分内容已失效,最新完整中文教程及代码请查看 https://github.com/WillieWangWei/SwiftUI-Tutorials
微信技术群
SwiftUI
代表未来构建 App 的方向,欢迎加群一起交流技术,解决问题。
加群现在需要申请了,可以先加我微信,备注 “SwiftUI”,我会拉你进群。
绘制 Path 和 Shape
用户访问列表中的地标时应当获得徽章,为此,我们需要创建徽章。在本文中,我们将通过组合
paths
和shapes
来创建徽章,然后把它和另一个表示位置的shape
叠在一起。我们可以尝试使用
overlaid
符号来给不同类型的地标创建多个徽章,修改它的重复次数或更改各种角度和比例。下载项目文件并按照以下步骤操作,也可以打开已完成的项目自行浏览代码。
- 预计完成时间:25 分钟
- 项目文件:下载
1. 创建一个 Badge View
首先我们创建一个使用 SwiftUI
中矢量绘图 API 的徽章 view 。
1.1 选择 File
> New
> File
,从 iOS Templates
中选择 SwiftUI View
。单击 Next
,命名为 Badge
,单击 Create
。
1.2 在定义徽章的 shape
前,先让 Badge view 显示 Badge
。
Badge.swift
import SwiftUI
struct Badge: View {
var body: some View {
Text("Badge")
}
}
#if DEBUG
struct Badge_Previews: PreviewProvider {
static var previews: some View {
Badge()
}
}
#endif
2. 绘制 Badge 的背景
用 SwiftUI
中的图形 API 绘制自定义的徽章 shape
。
2.1 查看 HexagonParameters.swift
文件中的代码。
HexagonParameters
结构体定义了绘制徽章的六边形 shape
的细节,我们不用修改这些数据,直接使用它们来指定绘制徽章的线条和曲线的控制点。
HexagonParameters.swift
import SwiftUI
struct HexagonParameters {
struct Segment {
let useWidth: (CGFloat, CGFloat, CGFloat)
let xFactors: (CGFloat, CGFloat, CGFloat)
let useHeight: (CGFloat, CGFloat, CGFloat)
let yFactors: (CGFloat, CGFloat, CGFloat)
}
static let adjustment: CGFloat = 0.085
static let points = [
Segment(
useWidth: (1.00, 1.00, 1.00),
xFactors: (0.60, 0.40, 0.50),
useHeight: (1.00, 1.00, 0.00),
yFactors: (0.05, 0.05, 0.00)
),
Segment(
useWidth: (1.00, 1.00, 0.00),
xFactors: (0.05, 0.00, 0.00),
useHeight: (1.00, 1.00, 1.00),
yFactors: (0.20 + adjustment, 0.30 + adjustment, 0.25 + adjustment)
),
Segment(
useWidth: (1.00, 1.00, 0.00),
xFactors: (0.00, 0.05, 0.00),
useHeight: (1.00, 1.00, 1.00),
yFactors: (0.70 - adjustment, 0.80 - adjustment, 0.75 - adjustment)
),
Segment(
useWidth: (1.00, 1.00, 1.00),
xFactors: (0.40, 0.60, 0.50),
useHeight: (1.00, 1.00, 1.00),
yFactors: (0.95, 0.95, 1.00)
),
Segment(
useWidth: (1.00, 1.00, 1.00),
xFactors: (0.95, 1.00, 1.00),
useHeight: (1.00, 1.00, 1.00),
yFactors: (0.80 - adjustment, 0.70 - adjustment, 0.75 - adjustment)
),
Segment(
useWidth: (1.00, 1.00, 1.00),
xFactors: (1.00, 0.95, 1.00),
useHeight: (1.00, 1.00, 1.00),
yFactors: (0.30 + adjustment, 0.20 + adjustment, 0.25 + adjustment)
)
]
}
2.2 在 Badge.swift
中,给徽章添加一个 Path shape
,然后调用 fill()
方法把 shape
转换成一个 view 。
我们可以使用 path
组合直线、曲线和其他绘图单元来形成更复杂的形状,如这里徽章的六边形背景。
Badge.swift
import SwiftUI
struct Badge: View {
var body: some View {
Path { path in
}
.fill(Color.black)
}
}
#if DEBUG
struct Badge_Previews: PreviewProvider {
static var previews: some View {
Badge()
}
}
#endif
2.3 给 path
添加起始点。
move(to:)
方法把绘制光标移动到一个 shape
的边上,就像钢笔或铅笔悬停在该位置,等待开始绘制。
Badge.swift
import SwiftUI
struct Badge: View {
var body: some View {
Path { path in
var width: CGFloat = 100.0
let height = width
path.move(to: CGPoint(x: width * 0.95, y: height * 0.20))
}
.fill(Color.black)
}
}
#if DEBUG
struct Badge_Previews: PreviewProvider {
static var previews: some View {
Badge()
}
}
#endif
2.4 绘制 shape
数