Reputation: 1023
I want to add Label on UIImage
, for this I have used One Label And adding this on Image Using imgImage.addSubview(txtLabel)
.Now I want to Save That Image in Galley. For Saving the Image I have Used below method.
@IBAction func btnSave(_ sender: AnyObject) {
UIImageWriteToSavedPhotosAlbum(imgImage.image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
But It will not saving image with Label. How can I achieve it.
Please Help
Thanks!
Upvotes: 2
Views: 1058
Reputation: 1061
Try:
extension UIImageView {
func makeImage() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
This basically takes a snapshot from your UIImageView
.
Upvotes: 0
Reputation: 6067
you can render image layer with text
like this // imageWithLabel handle final image
txtLabel.backgroundColor = UIColor.clearColor()
txtLabel.textAlignment = .Center
txtLabel.textColor = UIColor.whiteColor()
txtLabel.text = text
UIGraphicsBeginImageContextWithOptions(txtLabel.bounds.size, false, 0);
imgImage.layer.renderInContext(UIGraphicsGetCurrentContext()!)
label.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let imageWithLabel = UIGraphicsGetImageFromCurrentImageContext() // here is final image
UIGraphicsEndImageContext();
Upvotes: 1
Reputation: 16456
You can't use addsubview
there You need to draw it. Here is Sample code.
UIGraphicsBeginImageContext(img1.size);
//draw image1
[img1 drawInRect:CGRectMake(0, 0, img1.size.width, img1.size.height)];
//draw label
[label drawTextInRect:CGRectMake((img1.size.width - label.frame.size.width)/2, (img1.size.height - label.frame.size.height)/2, label.frame.size.width, label.frame.size.height)];
//get the final image
UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Upvotes: 1