How to add Watermark on UIImage in swift


Hello,

Today we are going to learn how to add watermark(Text/ Sign) on UIImage. This is a simple way to add text in particular position.

Implement this function in UIImage extension

#01 Implement Add Text on Image

// MARK: - Adding texts/ Water mark on image
    func addTextOnImage(drawText text: String, atPoint point: CGPoint? = nil) -> UIImage {
        let textColor = UIColor.white
        let textFont = UIFont.custom(.bold, 40)
        
        let scale = UIScreen.main.scale
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        
        let textFontAttributes: [NSAttributedString.Key : Any] = [NSAttributedString.Key.font: textFont,
                                                                  NSAttributedString.Key.foregroundColor: textColor,
                                                                  NSAttributedString.Key.backgroundColor: UIColor.black.withAlphaComponent(0.3)]
        draw(in: CGRect(origin: CGPoint.zero, size: size))
        
        let rect = CGRect(origin: CGPoint(x: 20, y: size.height - 120), size: size)
        text.draw(in: rect, withAttributes: textFontAttributes)
        
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return newImage ?? UIImage()
    }

Call the function like .addTextOnImage(drawText: "Happy Coding !")

Hope you learn this logic today. Implement in your project and enjoy.

Thanks,

Happy Coding !