-
-
Save getaclue00/dbd7ac14390c52c6ec7bde4c07e70544 to your computer and use it in GitHub Desktop.
This will allow you to take a screenshot of a UIView, but more importantly only a section of that view
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Screenshot.swift | |
// | |
// 1) Take a picture of a UIView | |
// 2) Take a picture of a UIView's subframe. EG. Fullscreen UIView with a | |
// small square box in the middle, it will only save what's visible in the box frame | |
// but not the box itself | |
import Foundation | |
import UIKit | |
extension UIView { | |
class func image(view: UIView, subview: UIView? = nil) -> UIImage? { | |
UIGraphicsBeginImageContextWithOptions(view.frame.size, false, 0) | |
view.drawHierarchy(in: view.frame, afterScreenUpdates: true) | |
var image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! | |
UIGraphicsEndImageContext() | |
if(subview != nil){ | |
var rect = (subview?.frame)! | |
rect.size.height *= image.scale //MOST IMPORTANT | |
rect.size.width *= image.scale //TOOK ME DAYS TO FIGURE THIS OUT | |
let imageRef = image.cgImage!.cropping(to: rect) | |
image = UIImage(cgImage: imageRef!, scale: image.scale, orientation: image.imageOrientation) | |
} | |
return image | |
} | |
func image() -> UIImage? { | |
return UIView.image(view: self) | |
} | |
func image(withSubview: UIView) -> UIImage? { | |
return UIView.image(view: self, subview: withSubview) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment