图形上下文的栈操作(保存和恢复)

图形上下文的栈操作
1、在对图形上下文进行操作之前先保存到栈
CGContextSaveState(图形上下文),相当于在内存中开辟一块区域用来存放图形上下文最原始的状态
2、操作图形上下文(栈操作)
3、添加路径(会受栈操作影响)
4、恢复图形上下文
CGcontextRestoreGState
5、添加路径(不受栈操作影响)
6、渲染
细节:oc的路径,与c的渲染混用时,属性设置用c的方式设置,如线宽等
 
下面贴到swift版代码:
 1 override func draw(_ rect: CGRect) {
 2         let context = UIGraphicsGetCurrentContext()
 3         
 4         // MARK: - 栈操作,在线图形上下文进行其他操作之前,先保存到栈
 5         // 相当于在内存中开辟一块儿区域,用来存放图形上下文最原始的状态
 6         context?.saveGState()
 7         
 8         
 9         // MARK: - 注意:矩阵操作一定要在添加路径之前设置
10         
11         // 旋转 - 逆时针旋转-M_PI_4(以原点为基准)
12         context?.rotate(by: CGFloat(-M_PI_4))
13         
14         // 平移 - 往左下角(以原点为基准)
15         context?.translateBy(x: 50, y: 50)
16         
17         // 缩放 - 宽高各缩小一半(以原点为基准)
18         context?.scaleBy(x: 0.5, y: 0.5)
19         
20         let borderPath = UIBezierPath(rect: rect)
21         
22         let rectPath = UIBezierPath(rect: CGRect(x: 10, y: 10,  200, height: 200))
23         
24         let circlePath = UIBezierPath(ovalIn: CGRect(x: 10, y: 210,  200, height: 200))
25     
26         context?.addPath(rectPath.cgPath)
27         context?.addPath(circlePath.cgPath)
28         
29         // MARK: - 想回到原始效果,恢复图形上下文状态 -> 相当于从栈拿出最原始的状态
30         context?.restoreGState()
31         context?.addPath(borderPath.cgPath)
32         
33         
34         // MARK: - 注意:OC的路径,与C的渲染混用时,设置属性时需要用C的方式
35         // borderPath.lineWidth = 20 // OC设置的属性无效
36         context?.setLineWidth(2)
37         
38         context?.strokePath()
39     }
原文地址:https://www.cnblogs.com/panda1024/p/6256266.html