swiftuiimageuigraphicscontext

How can I add a watermark to an image using this code?


I know there are several other ways to do this; I don't want to import anything that I don't need to. If someone can help me with his code, that would be great.

Currently, it is only saving the original image without the watermark image.

extension UIImage {

    class func imageWithWatermark(image1: UIImageView, image2: UIImageView) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(image1.bounds.size, false, 0.0)
        image2.layer.renderInContext(UIGraphicsGetCurrentContext()!)
        image1.layer.renderInContext(UIGraphicsGetCurrentContext()!)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
}

func addWatermark() {
    let newImage = UIImage.imageWithWatermark(imageView, image2: watermarkImageView)
    UIImageWriteToSavedPhotosAlbum(newImage, nil, nil, nil)
}

EDIT: I've got the watermark appearing on the saved images.

I had to switch the order of the layers:

 image1.layer.renderInContext(UIGraphicsGetCurrentContext()!)
 image2.layer.renderInContext(UIGraphicsGetCurrentContext()!)

HOWEVER, it is not appearing in the correct place.It seems to always appear in the center of the image.


Solution

  • SWIFT 4 Use this

    let backgroundImage = imageData!
    let watermarkImage = #imageLiteral(resourceName: "jodi_url_icon")
    
    let size = backgroundImage.size
    let scale = backgroundImage.scale
    
    UIGraphicsBeginImageContextWithOptions(size, false, scale)
    backgroundImage.draw(in: CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height))
    watermarkImage.draw(in: CGRect(x: 10, y: 10, width: size.width, height: size.height - 40))
    
    let result = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    

    Use result to UIImageView, tested.