Implementing electronic signature on IOS

Time:2021-6-5

This example for you to share the specific code of IOS electronic signature, for your reference, the specific content is as follows

Implementation principle

1. Use drag gesture record to get user signature path
2. When the user contacts the screen for the first time, a new uibezierpath is generated and added to the array. Set the contact point as the starting point. Add lines for uibezierpath during finger dragging, and redraw to generate continuous lines
3. Finger slide in the continuous re drawing, the formation of signature effect
4. Signature completed, converted to uiimage save

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) {
 //Get current point
 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()
 }

 //Redraw according to uibezierpath
 override func draw(_ rect: CGRect) {

 for path in pathArray {
 //Signature color
 UIColor.black.set()
 path.stroke()
 }
 }

 //Empty
 func clearSign() {
 pathArray.removeAll()
 self.setNeedsDisplay()
 }

 //Revocation
 func undoSign() {
 guard pathArray.count > 0 else {
 return
 }
 pathArray.removeLast()
 self.setNeedsDisplay()
 }

 ///Convert signature to image
 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
 }
}

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.

Recommended Today

What is “hybrid cloud”?

In this paper, we define the concept of “hybrid cloud”, explain four different cloud deployment models of hybrid cloud, and deeply analyze the industrial trend of hybrid cloud through a series of data and charts. 01 introduction Hybrid cloud is a computing environment that integrates multiple platforms and data centers. Generally speaking, hybrid cloud is […]