Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This will allow you to take a screenshot of a UIView, but more importantly only a section of that view
//
// 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)
}
}
@CodeIn5Dimensions

This comment has been minimized.

Copy link

CodeIn5Dimensions commented Feb 14, 2017

does this save to camera roll?

@CodeIn5Dimensions

This comment has been minimized.

Copy link

CodeIn5Dimensions commented Feb 14, 2017

also, how would i call this with a button?

@perceptinfotech

This comment has been minimized.

Copy link

perceptinfotech commented May 2, 2018

is capture my screen during video recording ?

@dhoerl

This comment has been minimized.

Copy link

dhoerl commented Feb 14, 2020

You can do this simpler by shifting the UIView. Think of a printed photo, and a matchbox. The Matchbox should cover the section you want, and its anchored to the top left of the image. To get it into the middle somewhere, you move the paper to the left and up, leaving the matchbox where it is. In code, to do this, you create a CGRect with negative x and y coordinates, but use the view's size alone.

I took this code and did the above modifications to it: https://gist.github.com/dhoerl/ea583ed8e9e94a6a44e276dc2ba55390

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.