实现功能如下:
1,页面上方提供一个签名区域(UIView),用户可以在这个区域手写签字。
3,点击“保存签名”,会将用户签名保存到设备相册中。
--- DrawSignatureView.swift (签名视图组件) ---
代码如下 | 复制代码 |
import UIKit public class DrawSignatureView: UIView { // 公共属性 public var lineWidth: CGFloat = 2.0 { didSet { self.path.lineWidth = lineWidth } } public var strokeColor: UIColor = UIColor.blackColor() public var signatureBackgroundColor: UIColor = UIColor.whiteColor() // 私有属性 private var path = UIBezierPath() private var pts = [CGPoint](count: 5, repeatedValue: CGPoint()) private var ctr = 0 // Init override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = self.signatureBackgroundColor self.path.lineWidth = self.lineWidth } // Init required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.backgroundColor = self.signatureBackgroundColor self.path.lineWidth = self.lineWidth } // Draw override public func drawRect(rect: CGRect) { self.strokeColor.setStroke() self.path.stroke() } // 触摸签名相关方法 override public func touchesBegan(touches: Set if let firstTouch = touches.first{ let touchPoint = firstTouch.locationInView(self) self.ctr = 0 self.pts[0] = touchPoint } } override public func touchesMoved(touches: Set if let firstTouch = touches.first{ let touchPoint = firstTouch.locationInView(self) self.ctr++ self.pts[self.ctr] = touchPoint if (self.ctr == 4) { self.pts[3] = CGPointMake((self.pts[2].x + self.pts[4].x)/2.0, (self.pts[2].y + self.pts[4].y)/2.0) self.path.moveToPoint(self.pts[0]) self.path.addCurveToPoint(self.pts[3], controlPoint1:self.pts[1], controlPoint2:self.pts[2]) self.setNeedsDisplay() self.pts[0] = self.pts[3] self.pts[1] = self.pts[4] self.ctr = 1 } self.setNeedsDisplay() } } override public func touchesEnded(touches: Set if self.ctr == 0{ let touchPoint = self.pts[0] self.path.moveToPoint(CGPointMake(touchPoint.x-1.0,touchPoint.y)) self.path.addLineToPoint(CGPointMake(touchPoint.x+1.0,touchPoint.y)) self.setNeedsDisplay() } else { self.ctr = 0 } } // 签名视图清空 public func clearSignature() { self.path.removeAllPoints() self.setNeedsDisplay() } // 将签名保存为UIImage public func getSignature() ->UIImage { UIGraphicsBeginImageContext(CGSizeMake(self.bounds.size.width, self.bounds.size.height)) self.layer.renderInContext(UIGraphicsGetCurrentContext()!) let signature: UIImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return signature } } |
--- ViewController.swift (使用样例) ---
代码如下 | 复制代码 |
import UIKit |