Skip to content

Instantly share code, notes, and snippets.

@nitrag
Created November 21, 2016 05:16
Show Gist options
  • Select an option

  • Save nitrag/b3117a4b6b8e89fdbc12b98029cf98f8 to your computer and use it in GitHub Desktop.

Select an option

Save nitrag/b3117a4b6b8e89fdbc12b98029cf98f8 to your computer and use it in GitHub Desktop.

Revisions

  1. nitrag created this gist Nov 21, 2016.
    42 changes: 42 additions & 0 deletions Screenshot.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    //
    // 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)
    }
    }