Search code examples
iosimageswiftgithubuigraphicscontext

YPDrawSignatureView, Capturing/Saving a Signature in an iOS App


I'm using the YPDrawSignatureView custom class on Github (https://github.com/yuppielabel/YPDrawSignatureView), and I set my application up to present modally a new view with the ability to sign your name and save/cancel the image.

I'm using the default save function in the class, but I have absolutely no idea how it works or where it saves to.

Here's the code for that function:

       // MARK: Save the Signature as an UIImage
func getSignature() ->UIImage {
    UIGraphicsBeginImageContext(CGSizeMake(self.bounds.size.width, self.bounds.size.height))
    self.layer.renderInContext(UIGraphicsGetCurrentContext())
    var signature: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return signature
}

This is how I'm calling it:

        @IBAction func saveButton(sender: UIButton) {
    SignatureImage = signatureCaptureField!.getSignature()
    dismissViewControllerAnimated(true, completion: nil)
}

I wish to save that signature as an image, and make it appear on the main View of the application (as a signature for a form). Where is it saved to and from where and how am I able to access it in that view?

Thanks!


Solution

  • getSignature() should have a return of UIImage. This is the stored image of the signature.

    @IBAction func saveButton(sender: UIButton) {
        let image = signatureCaptureField!.getSignature()
        dismissViewControllerAnimated(true, completion: nil)
    }
    

    You can access the NSData of the image and save it:

    var imageData = UIImagePNGRepresentation(image)
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    let destinationPath = documentsPath.stringByAppendingPathComponent("filename.png")
    imageData.writeToFile(destinationPath, atomically: true)
    

    Or create a UIImageView to display it back to the user:

    let imageView = UIImageView(image: image)
    imageView.sizeToFit()
    view.addSubview(imageView)