StuartM StuartM - 7 months ago 34
Swift Question

Creating a custom image with UIImage and other attributes

I am looking to create a custom image in

iOS
. 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
UIImage
. 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
XIB
which controls the layout and init this off screen, use a snapshot to create the finished
UIImage
and
dealloc
the view. Or would it be better to use
CGContextDrawImage
? 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

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
    UIGraphicsBeginImageContext((loveIs?.bounds.size)!)
    loveIs?.layer.renderInContext(UIGraphicsGetCurrentContext()!)
    
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    UIImageWriteToSavedPhotosAlbum(image, self, nil, nil)
    
Comments