Created
March 7, 2015 23:49
-
-
Save mattrajca/89ab8e8efbd497677276 to your computer and use it in GitHub Desktop.
Blurring images with UIVisualEffectView
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
// | |
// BlurredImageGenerator.swift | |
// | |
// Copyright (c) 2015 Matt Rajca. All rights reserved. | |
// | |
import UIKit | |
func generateBlurredImageFromImage(image: UIImage) -> UIImage { | |
let sourceImageRect = CGRectMake(0, 0, image.size.width, image.size.height) | |
var window: UIWindow! = UIWindow(frame: sourceImageRect) | |
window.windowLevel = -1000 // place the temporary window offscreen | |
let parent = UIView(frame: sourceImageRect) | |
let imageView = UIImageView(frame: sourceImageRect) | |
imageView.image = image | |
let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .Dark)) | |
blurView.frame = sourceImageRect | |
imageView.addSubview(blurView) | |
parent.addSubview(imageView) | |
let vc = UIViewController() | |
vc.view = parent | |
window.rootViewController = vc | |
window.makeKeyAndVisible() | |
UIGraphicsBeginImageContextWithOptions(sourceImageRect.size, false, 1 /* don't blow up the image coordinates */) | |
window.drawViewHierarchyInRect(sourceImageRect, afterScreenUpdates: true) | |
let snapshotImage = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
window = nil | |
return snapshotImage | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment