ios - How to take screenshot of portion of UIView? -


i want user go on app , take screenshot of app after pressing button programmatically in swift. know uigraphicsgetimagefromcurrentimagecontext() takes screenshot don't want picture of entire screen. want rectangle pop (sort of crop tool) , user can drag , resize rectangle take screenshot of part of screen. want rectangle go on wkwebview , crop pic of web view.

the standard snapshot technique drawviewhierarchyinrect. , portion of image, can use cgimagecreatewithimageinrect.

thus, in swift 2:

extension uiview {      /// create snapshot     ///     /// - parameter rect: `cgrect` of portion of view return. if `nil` (or omitted),     ///                   return snapshot of whole view.     ///     /// - returns: returns `uiimage` of specified portion of view.      func snapshot(of rect: cgrect? = nil) -> uiimage? {         // snapshot entire view          uigraphicsbeginimagecontextwithoptions(bounds.size, opaque, 0)         drawviewhierarchyinrect(bounds, afterscreenupdates: true)         let wholeimage = uigraphicsgetimagefromcurrentimagecontext()         uigraphicsendimagecontext()          // if no `rect` provided, return image of whole view          guard let rect = rect, let image = wholeimage else { return wholeimage }          // otherwise, grab specified `rect` of image          let scale = image.scale         let scaledrect = cgrect(x: rect.origin.x * scale, y: rect.origin.y * scale, width: rect.size.width * scale, height: rect.size.height * scale)         guard let cgimage = cgimagecreatewithimageinrect(image.cgimage!, scaledrect) else { return nil }         return uiimage(cgimage: cgimage, scale: scale, orientation: .up)     }  } 

in swift 3:

extension uiview {      /// create snapshot     ///     /// - parameter rect: `cgrect` of portion of view return. if `nil` (or omitted),     ///                   return snapshot of whole view.     ///     /// - returns: returns `uiimage` of specified portion of view.      func snapshot(of rect: cgrect? = nil) -> uiimage? {         // snapshot entire view          uigraphicsbeginimagecontextwithoptions(bounds.size, isopaque, 0)         drawhierarchy(in: bounds, afterscreenupdates: true)         let wholeimage = uigraphicsgetimagefromcurrentimagecontext()         uigraphicsendimagecontext()          // if no `rect` provided, return image of whole view          guard let image = wholeimage, let rect = rect else { return wholeimage }          // otherwise, grab specified `rect` of image          let scale = image.scale         let scaledrect = cgrect(x: rect.origin.x * scale, y: rect.origin.y * scale, width: rect.size.width * scale, height: rect.size.height * scale)         guard let cgimage = image.cgimage?.cropping(to: scaledrect) else { return nil }         return uiimage(cgimage: cgimage, scale: scale, orientation: .up)     }  } 

and use it, can do:

if let image = webview.snapshot(of: rect) {     // `image` here } 

Comments