iOS實(shí)現(xiàn)電子簽名
本文實(shí)例為大家分享了iOS實(shí)現(xiàn)電子簽名的具體代碼,供大家參考,具體內(nèi)容如下
實(shí)現(xiàn)原理
1、使用拖動手勢記錄獲取用戶簽名路徑.2、當(dāng)用戶初次接觸屏幕,生成一個(gè)新的UIBezierPath,并加入數(shù)組中.設(shè)置接觸點(diǎn)為起點(diǎn).在手指拖動過程中為UIBezierPath添加線條,并重新繪制,生成連續(xù)的線.3、手指滑動中不斷的重新繪制,形成簽名效果.4、簽名完成,轉(zhuǎn)化為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) { // 獲取當(dāng)前點(diǎn) 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() } // 根據(jù) 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() } /// 簽名轉(zhuǎn)化為圖片 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 }}
源碼
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 不要在HTML中濫用div2. HTTP協(xié)議常用的請求頭和響應(yīng)頭響應(yīng)詳解說明(學(xué)習(xí))3. Electron調(diào)用外接攝像頭并拍照上傳實(shí)現(xiàn)詳解4. React優(yōu)雅的封裝SvgIcon組件示例5. HTML5實(shí)戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)6. CSS百分比padding制作圖片自適應(yīng)布局7. TypeScript實(shí)現(xiàn)十大排序算法之歸并排序示例詳解8. vue前端RSA加密java后端解密的方法實(shí)現(xiàn)9. 深入了解React中的合成事件10. CSS清除浮動方法匯總
