Skip to content

Instantly share code, notes, and snippets.

@leeprobert
Created July 5, 2016 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leeprobert/bd1409cc4912c0f3dd4cbd3d61a672c8 to your computer and use it in GitHub Desktop.
Save leeprobert/bd1409cc4912c0f3dd4cbd3d61a672c8 to your computer and use it in GitHub Desktop.
CoreImage extensions
/*
Extension for UIView for taking a snapshot and blurring it using CoreImage filters.
*/
extension UIView {
func blurredSnapshot() -> UIImage {
func toCIImage(image: UIImage) -> CIImage {
return image.CIImage ?? CIImage(CGImage: image.CGImage!)
}
func toUIImage(image: CIImage) -> UIImage {
return UIImage(CIImage: image)
}
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)
drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
var finalImage:UIImage?
if let ciImage:CIImage = toCIImage(image) {
if let blurredImage:CIImage = ciImage.imageByApplyingFilter("CIGaussianBlur", withInputParameters: [kCIInputRadiusKey : 20]){
// crop blurred image so it is the same as the source snapshot. Otherwise it is larger because of the blurring
if let croppedBlurredImage:CIImage = blurredImage.imageByCroppingToRect(ciImage.extent){
finalImage = toUIImage(croppedBlurredImage)
}
}
}
return finalImage ?? image
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment