Created
July 5, 2016 11:23
-
-
Save leeprobert/bd1409cc4912c0f3dd4cbd3d61a672c8 to your computer and use it in GitHub Desktop.
CoreImage extensions
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
/* | |
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