2

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

Ollie
  • 1,926
  • 1
  • 20
  • 35
sdd
  • 889
  • 8
  • 29
  • if the part of the screen is a UIView, check this link http://stackoverflow.com/questions/30696307/how-to-convert-a-uiview-to-a-image – Sri Hari YS Apr 05 '17 at 13:41

3 Answers3

1

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.

Saqib Omer
  • 5,387
  • 7
  • 50
  • 71
0

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

exampleImageView.snapshotViewAfterScreenUpdates(false)
Valentin
  • 3,272
  • 1
  • 14
  • 22
  • Returns a new view object containing a snapshot of the screen’s rendered contents. For further info look Apple Docs: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIScreen_Class/index.html – Valentin Jan 15 '15 at 16:07
0

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)  
}
Raksha Saini
  • 604
  • 12
  • 28