一、图形绘制
首先,在定义SwiftUI组件时,我们可以通过路径的定义绘制其要表现的UI图形,例如要在页面上显示一个菱形图形,示例代码如下:
struct DrawTestView:View {
var body: some View {
Path { path in
let width = 200
let height = 200
path.move(to: CGPoint(x: width, y: height))
path.addLine(to: CGPoint(x: 100, y: 400))
path.addLine(to: CGPoint(x: 200, y: 600))
path.addLine(to: CGPoint(x: 300, y: 400))
}.fill(Color.red)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
DrawTestView()
}
}
效果如下图所示:
上面的代码很好理解,使用Path在定义View时,move方法用来进行绘制点的移动,简单理解,如果我们将图形的绘制类比与用笔作画,则move方法的作用就是移动笔尖的位置。addLine方法用来向视图上画一条线,定义完了路径后,调用fill方法用来进行图形内部颜色的填充。如上代码所示,实际上我们只画了三条线,系统默认将三条线及最后一个点与原点的连线组成的图形内部进行了颜色的填充,如果我们不对内部进行颜色填充,只将线的颜色显示出来,就更加直观了,代码如下:
struct DrawTestView:View {
var body: some View {
Path { path in
let width = 200
let height = 200
path.move(to: CGPoint(x: width, y: height))
path.addLine(to: CGPoint(x: 100, y: 400))
path.addLine(to: CGPoint(x: 200, y: 600))
path.addLine(to: CGPoint(x: 300, y: 400))
}.stroke(Color.red,lineWidth: 10)
}
}
效果如下图所示:
与addLine的使用方法类似,我们还可以通过添加矩形、椭圆、贝塞尔曲线等等方法来绘制图形,示例代码如下:
struct DrawTestView:View {
var body: some View {
Path { path in
let width = 200
let height = 200
path.move(to: CGPoint(x: width, y: height))
path.addLine(to: CGPoint(x: 100, y: 400))
path.addLine(to: CGPoint(x: 200, y: 600))
path.addLine(to: CGPoint(x: 300, y: 400))
path.addRect(CGRect(x: 20, y: 20, width: 30, height: 30))
path.addEllipse(in: CGRect(x: 60, y: 20, width: 60, height: 30))
path.addCurve(to: CGPoint(x: 100, y: 100), control1: CGPoint(x: 160, y: 100), control2: CGPoint(x: 60, y: 80))
path.addRoundedRect(in: CGRect(x: 140, y: 20, width: 50, height: 40), cornerSize: CGSize(width: 20, height: 20))
}.stroke(Color.red,lineWidth: 3)
}
}
效果如下图所示: