本文实例为大家分享了iOS实现电子签名的具体代码,供大家参考,具体内容如下
实现原理
1、使用拖动手势记录获取用户签名路径.
2、当用户初次接触屏幕,生成一个新的UIBezierPath,并加入数组中.设置接触点为起点.在手指拖动过程中为UIBezierPath添加线条,并重新绘制,生成连续的线.
3、手指滑动中不断的重新绘制,形成签名效果.
4、签名完成,转化为UIImage保存.
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://www.zxbcw.cn/post/197805/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)