IOS Swift实现手写签名,签字功能 并转为图片
首先自定义首先签名View
class SignatureView:UIView {
let lineWidth = 1 //线条宽度
let lineColor:UIColor = .black//线条颜色
var currentPath:UIBezierPath? = nil
var paths:[UIBezierPath] = []
init(){
super.init(frame: CGRect.zero)
isUserInteractionEnabled = true
}
required init ?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
然后监听当前view的点击和移动
override func touchesBegan( _ touches: Set<UITouch>, with event: UIEvent?) {
let currentPoint = getPoint(touches)
let path = UIBezierPath()
path.lineWidth = 1
path.move(to: currentPoint)
paths.append(path)
currentPath = path
}
override func touchesMoved( _ touches: Set<UITouch>, with event: UIEvent?) {
let currentPoint = getPoint(touches)
currentPath?.addLine(to:currentPoint)
setNeedsDisplay()
}
接下来是根据触摸点获取坐标,以及转为图片
//获取点前点击坐标
func getPoint( _ touches:Set<UITouch>) -> CGPoint{
let touch = (touches as NSSet).anyObject() as! UITouch
return touch.location(in: self)
}
//设置线条颜色
override func draw( _ rect: CGRect) {
guard paths.count != 0 else {
return
}
for path in paths {
lineColor.set()
path.stroke()
}
}
//轻触当前签名
func clear(){
paths.removeAll()
setNeedsDisplay()
}
//转为图片
func confirmToImage() ->UIImage?{
UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
self.layer.render(in: context)
guard let image = UIGraphicsGetImageFromCurrentImageContext() else
{ return nil }
UIGraphicsEndImageContext()
saveImage(image: image)
return image
}
//保存相册方法
private func saveImage(image: UIImage) {
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAsset(from: image)
}, completionHandler: { [(isSuccess, error) in
DispatchQueue.main.async {
if isSuccess {// 成功
PFHUDView.show("保存成功")
}
}
})
}