本文实例为大家分享了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
}
}
您可能感兴趣的文章:IOS 签名错误codesign failed with exit code 1解决方法iOS APP签名机制原理详解iOS 超级签名之描述文件的实现过程iOS mobileconfig配置文件进行签名的配置方法