本文实例为大家分享了iOS实现电子签名的具体代码,供大家参考,具体内容如下
实现原理
1、使用拖动手势记录获取用户签名路径.
2、当用户初次接触屏幕,生成一个新的UIBezierPath,并加入数组中.设置接触点为起点.在手指拖动过程中为UIBezierPath添加线条,并重新绘制,生成连续的线.
3、手指滑动中不断的重新绘制,形成签名效果.
4、签名完成,转化为UIImage保存.
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
class CXGSignView: UIView { var path: UIBezierPath? var pathArray: [UIBezierPath] = [] override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.gray setupSubviews() } required init?(coder aDecoder: NSCoder) { fatalError( "init(coder:) has not been implemented" ) } func setupSubviews() { let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panGestureRecognizerAction(_:))) self.addGestureRecognizer(panGestureRecognizer) } @objc func panGestureRecognizerAction(_ sender: UIPanGestureRecognizer) { // 获取当前点 let currentPoint = sender.location(in: self) if sender.state == .began { self.path = UIBezierPath() path?.lineWidth = 2 path?.move(to: currentPoint) pathArray.append(path!) } else if sender.state == .changed { path?.addLine(to: currentPoint) } self.setNeedsDisplay() } // 根据 UIBezierPath 重新绘制 override func draw(_ rect: CGRect) { for path in pathArray { // 签名颜色 UIColor.black.set() path.stroke() } } // 清空 func clearSign() { pathArray.removeAll() self.setNeedsDisplay() } // 撤销 func undoSign() { guard pathArray.count > 0 else { return } pathArray.removeLast() self.setNeedsDisplay() } /// 签名转化为图片 func saveSignToImage() -> UIImage? { UIGraphicsBeginImageContextWithOptions(self.bounds.size, false , UIScreen.main.scale) guard let context = UIGraphicsGetCurrentContext() else { return nil } self.layer.render(in: context) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/CuiXg/article/details/109113720