sdd
sdd

Reputation: 877

Taking screenshot from part of screen in swift

I Need to take a screenshot of a part of the screen.

This is the code to take a screenshot of the full screen:

    UIGraphicsBeginImageContext(view.frame.size)
    view.layer.renderInContext(UIGraphicsGetCurrentContext())
    let imageRef = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

But how do I take a screenshot from just a part of the screen?

Thank you

Upvotes: 2

Views: 6115

Answers (3)

Raksha Saini
Raksha Saini

Reputation: 603

This is the best way to screenshot part of a screen. try that for twitter and facebook screenshot share functionality.

 func shareButtonClickedToTwitter() {
     UIGraphicsBeginImageContextWithOptions(CGSizeMake(100,150), false, 0)
     var image:UIImage = UIGraphicsGetImageFromCurrentImageContext();
     self.view?.drawViewHierarchyInRect(CGRectMake(-50, -50, self.frame.size.width, self.frame.size.height), afterScreenUpdates: true)
     var screenShot  = UIGraphicsGetImageFromCurrentImageContext()
     UIGraphicsEndImageContext()
     self.vc.showTWShare("I scored \(score) in Beanystalk can you do better? Available in App Store..", shareImage: screenShot)  
}

Upvotes: 0

Saqib Omer
Saqib Omer

Reputation: 5477

1: You need to define a context. eg:

UIGraphicsBeginImageContextWithOptions(self.messageTextView.bounds, true, 2.0 )

2: Draw image in context

self.messageTextView.drawViewHierarchyInRect(CGRect(x: 0, y: 0, width: self.messageTextView.bounds.width, height: self.messageTextView.bounds.height), afterScreenUpdates: false)

3: Use newly drawn image

var newImage = UIGraphicsGetImageFromCurrentImageContext()
self.someImageView.image = newImage

You can modify code to take screenshoot for your desired view.

Upvotes: 1

Valentin
Valentin

Reputation: 3302

You do it using .snapshotViewAfterScreenUpdates(BOOL). Like this:

exampleImageView.snapshotViewAfterScreenUpdates(false)

Upvotes: 0

Related Questions