Search code examples
swiftuiimagescreenshotcgimage

Cropping a screenshot in swift


I am trying to take a screenshot of the screen and crop a part out of that screenshot. the screenshot part is working perfect, but I can't make the cropping part work.

var image = self.view?.pb_takeSnapshot()

let croprect = CGRectMake(view.bounds.width/2, view.bounds.height/3.8, 
               view.bounds.width/2,    view.bounds.height/3.5)

    var imageRef = CGImageCreateWithImageInRect(CGImage(image), croprect) //Error: CGImage cannot be constructed because it has no accessible initializers
    var croppedImage = UIImage(CGImage: imageRef)

function that takes the screenshot:

func pb_takeSnapshot() -> UIImage {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.mainScreen().scale);

    self.drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)

    // old style: self.layer.renderInContext(UIGraphicsGetCurrentContext())

    let image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

My question: is there a way to do this without using CGImage, or is there a simple way to convert an UIImage to a CGImage?


Solution

  • UIImage in most cases contains a CGImage that you can directly access.

    In your case image is set using Optional Chaining and is of type UIImage? so you would need:

    UIImage?.CGImage

    to access the CGImage