UIBezierPath

使用UIBezierPath类可以创建基于矢量的路径,这个类在UIKit中。此类是Core Graphics框架关于path的一个封装。使用此类可以定义简单的形状,如椭圆或者矩形,或者有多个直线和曲线段组成的形状。
Image text

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class BezierPathView: UIView {
override func draw(_ rect: CGRect) {
// 画矩形
let bp = UIBezierPath(rect:CGRect(x: 10, y: 30, width: 30, height: 50))
UIColor.green.set()
bp.fill()
// 画椭圆(如果宽高相等则为圆)
let ovel = UIBezierPath(ovalIn: CGRect(x: 50, y: 30, width: 60, height: 40))
UIColor.red.set()
ovel.fill()
// 画圆角的矩形(圆角值为8)
let roundeRect1 = UIBezierPath(roundedRect: CGRect(x: 120, y: 30, width: 60, height: 40), cornerRadius: 8)
UIColor.orange.set()
roundeRect1.fill()
// 画矩形,指定某个或多个角设置圆角
let roundeRect2 = UIBezierPath(roundedRect: CGRect(x: 190, y: 30, width: 60, height: 40), byRoundingCorners: [.topLeft,.bottomRight], cornerRadii: CGSize(width: 20, height: 60))
UIColor.blue.set()
roundeRect2.fill()
// 画圆弧1
let arcPath = UIBezierPath(arcCenter: CGPoint(x: 50, y: 120), radius: 40, startAngle:2 * .pi, endAngle: .pi/2, clockwise: true)
UIColor.brown.set()
arcPath.stroke()
// 画圆弧2
let arcPath2 = UIBezierPath()
arcPath2.addArc(withCenter: CGPoint(x: 250, y: 120), radius: 40, startAngle: .pi, endAngle: .pi * 2, clockwise: false)
arcPath2.stroke()
// 二阶贝赛尔曲线(起点、终点、一个控制点)
let twoPath = UIBezierPath()
twoPath.move(to: CGPoint(x: 20, y: 250))
twoPath.addQuadCurve(to: CGPoint(x: 100, y: 250), controlPoint: CGPoint(x: 80, y: 180))
let twoPath1 = UIBezierPath()
twoPath1.move(to: CGPoint(x: 150, y: 250))
twoPath1.addQuadCurve(to: CGPoint(x: 230, y: 250), controlPoint: CGPoint(x: 190, y: 180))
twoPath1.append(twoPath) //拼接路径
UIColor.black.set()
twoPath1.lineWidth = 2.0
twoPath1.lineCapStyle = .square
twoPath1.lineJoinStyle = .round
twoPath1.stroke()
// 三阶贝赛尔曲线(起点、终点、两个控制点)
let threePath = UIBezierPath()
threePath.move(to: CGPoint(x: 20, y: 350))
threePath.addCurve(to: CGPoint(x: 300, y: 350), controlPoint1: CGPoint(x: 100, y: 250), controlPoint2: CGPoint(x: 180, y: 450))
UIColor.orange.set()
threePath.stroke()
}
}

圆弧起始点
Image text
二阶贝塞尔曲线示意图
Image text
三阶贝塞尔曲线示意图
Image text

打赏支持一下呗!