StuartM StuartM - 2 years ago 158
Swift Question

Creating a custom image with UIImage and other attributes

I am looking to create a custom image in

. The image would be used for sharing to social sites for example.

As an example, the user might select a photo which we have a reference to as a
. With this image we want to create another image with the original contained within it.

The idea is to create a polaroid style image with some writing/wording at the bottom. What is the best way to achieve this?

My first thought is to create a
which controls the layout and init this off screen, use a snapshot to create the finished
the view. Or would it be better to use
? The worry is the layout, if we have multiple items that require a specific layout is context drawing going to be easy to accomplish

Answer Source

I was able to create this image below: Polaroid

via the following method:

  1. Setup an XIB like a polaroid: Static Mine's pretty static, but you can use the File Owner and some other magic to set your image and text easily.

  2. Setup a class file with the following:

    import Foundation
    import UIKit
    class LoveIs: UIView {
    class func instanceFromNib() -> UIView {
        return UINib(nibName: "Polaroid", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! UIView
    }    }
  3. Setup your main view controller (one 'fetching' the image) like so:

    var loveIs: UIView? = nil
    loveIs = LoveIs.instanceFromNib()
    loveIs?.layer.borderColor = UIColor.darkGrayColor().CGColor
    loveIs?.layer.borderWidth = 5
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIImageWriteToSavedPhotosAlbum(image, self, nil, nil)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download