Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking a screenshot and adding a text/watermark on top in Swift

Tags:

ios

swift

swift2

Im trying to allow the ability for a user to share a screenshot of an App and share it. I have got the taking of a screenshot and sharing but was interested in finding out if anyone knew how to add a layer of text on top of that screenshot when it is being taken, kind of like a watermark.

Here I take the screenshot:

        let layer = UIApplication.sharedApplication().keyWindow!.layer
        let scale = UIScreen.mainScreen().scale
        UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);

        layer.renderInContext(UIGraphicsGetCurrentContext()!)
        let screenshot = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        let croppedImage = self.cropImage(screenshot)
        let activityViewController = UIActivityViewController(activityItems: [croppedImage], applicationActivities: nil)
        self.presentViewController(activityViewController, animated: true, completion: nil)

I crop the screenshot image in this function so it just shows middle of screen:

func cropImage(screenshot: UIImage) -> UIImage {
    let scale = screenshot.scale
    let imgSize = screenshot.size
    let screenHeight = UIScreen.mainScreen().bounds.height
    let bound = self.view.bounds.height
    let navHeight = self.navigationController!.navigationBar.frame.height
    let bottomBarHeight = screenHeight - navHeight - bound
    let crop = CGRectMake(0, 200, //"start" at the upper-left corner
        (imgSize.width - 1) * scale, //include half the width of the whole screen
        (imgSize.height - bottomBarHeight - 300) * scale) //include the height of the navigationBar and the height of view

    let cgImage = CGImageCreateWithImageInRect(screenshot.CGImage, crop)
    let image: UIImage = UIImage(CGImage: cgImage!)
    return image
}
like image 273
kelsheikh Avatar asked Oct 21 '25 00:10

kelsheikh


1 Answers

Yes it is possible to do that. Try adding subview to your image view like below

let newImageView = UIImageView(image : croppedImage)
let labelView = UILabel(frame: CGRectMake(30, 30, 100, 20)) //adjust frame to change position of water mark or text
labelView.text = "my text"
newImageView.addSubview(labelView)
UIGraphicsBeginImageContext(newImageView.frame.size)
newImageView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let watermarkedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
like image 186
Vishnu gondlekar Avatar answered Oct 22 '25 15:10

Vishnu gondlekar