2

I'm trying to save a label on top of an image using .WriteToFile .

Here's the code I'm using to save the image :

    let selectedImage: UIImage = image.image!
     let fileManager = NSFileManager.defaultManager()
     let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
     let filePathToWrite = "\(paths)/User_Profile_Image.png"
     let imageData: NSData = UIImagePNGRepresentation(selectedImage)!
     let jpgImageData = UIImageJPEGRepresentation(selectedImage, 1.0)
     fileManager.createFileAtPath(filePathToWrite, contents: jpgImageData, attributes: nil)
     // Check file saved successfully        
      let getImagePath = (paths as NSString).stringByAppendingPathComponent("User_Profile_Image.png")
     if (fileManager.fileExistsAtPath(getImagePath)) {
     print("FILE AVAILABLE");
  } else {
     print("FILE NOT AVAILABLE");
 }

But it only saves the image : screenshot of simulator and image saved

I'm trying to retrieve it by :

 if let pdfURL = NSBundle.mainBundle().URLForResource("User_Profile_Image", withExtension: "png", subdirectory: nil, localization: nil),data = NSData(contentsOfURL: pdfURL), baseURL = pdfURL.URLByDeletingLastPathComponent  {
       let webView = UIWebView(frame: CGRectMake(20,20,self.view.frame.size.width-40,self.view.frame.size.height-40))
    print("Hello World")
    webView.loadData(data, MIMEType: "application/pdf", textEncodingName:"", baseURL: baseURL)//application/
    self.view.addSubview(webView)
  }

But it isn't working. Any ideas?

Niall Kehoe
  • 379
  • 2
  • 5
  • 18

2 Answers2

3

In your current approach, you are placing a UILabel over the top of the image, this does not modify the image in anyway, the label just sits over it. To actually write the text on the image you need to use the Graphics context to actually draw the text on the image.

Have a look at the below code, this will take an image and write Hello World in white text in the bottom right corner.

class ViewController: UIViewController {

    @IBOutlet weak var imageVIew: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.


    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        let font = UIFont.boldSystemFontOfSize(30)
        let showText:NSString = "hello world"
        // setting attr: font name, color...etc.
        let attr = [NSFontAttributeName: font, NSForegroundColorAttributeName:UIColor.whiteColor()]
        // getting size
        let sizeOfText = showText.sizeWithAttributes(attr)

        let image = UIImage(named: "dog")
        let rect = CGRectMake(0, 0, image!.size.width, image!.size.height)

        UIGraphicsBeginImageContextWithOptions(CGSize(width: rect.size.width, height: rect.size.height), true, 0)

        // drawing our image to the graphics context
        image?.drawInRect(rect)
        // drawing text
        showText.drawInRect(CGRectMake(rect.size.width-sizeOfText.width-10, rect.size.height-sizeOfText.height-10, rect.size.width, rect.size.height), withAttributes: attr)

        // getting an image from it
        let newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext()

        self.imageVIew.image = newImage
    }
}

Once you have done this, you can just save the newImage as a file, or overwrite your existing one.

I used the bottom of this guide for reference, It's a while since I done anything like this

Scriptable
  • 19,402
  • 5
  • 56
  • 72
  • This answer won't work for me because I'm going to need to pinpoint 60 fields with labels. Image : http://postimg.org/image/ayg9ges63/. Can it be done through storyboard? – Niall Kehoe May 29 '16 at 15:00
  • unfortunately not, you cannot permanently merge images and text from within storyboard. The storyboard just helps you visually place components into the view, if you place items on top of another item, they are just layers, they don't actually get merged. you would need to write text onto the images yourself. what is it that you are trying to achieve? from the image you posted, if you are trying to replicate this form you would need to use labels/textfields and a custom checkbox component to display it. you would only try to save it when the user requested, then you would need to draw it – Scriptable May 29 '16 at 15:04
  • I'm trying to approach it using this method because the code I'm used to use : – Niall Kehoe May 29 '16 at 15:09
  • i understand, but like I say... storyboard just places items, it wont merge them. I think for what you are trying to do you shouldn't be creating a document in real time. you should create a visual representation of the form and store the data that comes from the form. You should look into creating a PDF document from iOS Views see this here https://concentricsky.com/blog/article/creating-multipage-pdf-document-uiviews-ios, or a more basic example: http://stackoverflow.com/questions/33503211/create-and-store-pdf-document-programmatically-using-swift-for-ios – Scriptable May 29 '16 at 15:13
  • image: http://postimg.org/image/67a02oqor/ . Won't recover. Question : http://stackoverflow.com/questions/35945469/how-to-recover-pdfs-from-writetofile-in-swift – Niall Kehoe May 29 '16 at 15:15
  • by recover you mean you cant read the file again? save the file to your applications documents directory and store the name you saved it with, then read it again using the same values? if you save as a PDF you need to read as PDF, you cannot load a PDF into an image view. – Scriptable May 29 '16 at 15:22
  • I'm planning on using a QLPreviewController but I haven't got that far yet because Xcode isn't finding the file. I tested this by adding a print statement. Image : http://postimg.org/image/bm7snp8rf/ – Niall Kehoe May 29 '16 at 15:29
  • this particular question should be answered already above, the issue you have now is reading the file which is your other question, I will try to help on that one – Scriptable May 29 '16 at 15:46
  • Thanks @scriptable – Niall Kehoe May 29 '16 at 17:36
0

Though the label is on top of the image view, it is not part of the image. You must render the label onto the image in an image context then grab the image from the context. That image will have the text on top of it. Save and retrieve that image and it should work.

Adam H.
  • 681
  • 3
  • 8