I am adding a UILabel over UIImageView and adding features like increase font size, change color etc. Now what i need is that after the editing is complete we are left with the UILabel with its properties like frame, color, fontsize etc.
I need to add the UILabel
over UIImage
to generate a new UIImage
.
Kindly suggest what needs to be done. Also correct me if i'm wrong.
I require to achieve something like this as an UIImage
The Black subview is the UIImage that i require to obtain
NOTE : This is absolutely not a duplicate of :
How do I add text to an image in iOS Swift as I have many attributes to take in account as the frame , its bounds , color, font size, alignment and scale etc. I can also not screenshot the view.
Solution :
Someone has voted it as a duplicate so I cannot post an answer separately. This solution worked for me perfectly.
I have created an extension for using it everywhere : import Foundation import UIKit
extension UIImage {
class func createImageWithLabelOverlay(label: UILabel,imageSize: CGSize, image: UIImage) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: imageSize.width, height: imageSize.height), false, 2.0)
let currentView = UIView.init(frame: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
let currentImage = UIImageView.init(image: image)
currentImage.frame = CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height)
currentView.addSubview(currentImage)
currentView.addSubview(label)
currentView.layer.render(in: UIGraphicsGetCurrentContext()!)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
}
Usage : Anywhere on your ViewController where you have the size and the label to add use it as follows -
let newImageWithOverlay = UIImage.createImageWithLabelOverlay(label: labelToAdd, imageSize: size, image: editedImage)