UIBlurEffect not working when trying to take screenshot programically in swift
Asked Answered
M

3

7

I've blurred my view programmatically and added a share extension with screenshot but the screenshot doesn't blur my view in the image. All programming in swift

Code for blurring

let blurEffect = UIBlurEffect(style:.Dark)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = imageView2.frame
self.view.addSubview(blurView)

Code for screenshot

UIGraphicsBeginImageContext(view.frame.size)
view.layer.renderInContext(UIGraphicsGetCurrentContext())
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

Thanks

Muimuir answered 14/5, 2015 at 11:25 Comment(0)
T
13

Try taking the screenshot this way:

UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0)
view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
Thorn answered 14/5, 2015 at 13:37 Comment(5)
Though could you help me, the status bar is missingMuimuir
Change view.drawViewHierarchy... to view.window?.drawViewHierarchy...Thorn
I don't know why you view would not have a window. Try using this: UIApplication.sharedApplication().delegate?.window.Thorn
This works perfectly for small views. For big views the screenshot just becomes a white image. Do you know why is this happening and solution for that ?Essary
This method is a bit slow. Use it wisely. When you don't need to capture the UIVisualEffectView, always use snapshotView(afterScreenUpdates: true)Mong
M
6

I just found Apple has actually documented on how to take a snapshot of UIVisualEffectView:

Capturing a Snapshot of a UIVisualEffectView Many effects require support from the window that hosts the UIVisualEffectView. Attempting to take a snapshot of only the UIVisualEffectView will result in a snapshot that does not contain the effect. To take a snapshot of a view hierarchy that contains a UIVisualEffectView, you must take a snapshot of the entire UIWindow or UIScreen that contains it.

Thanks!

Montelongo answered 2/11, 2016 at 2:13 Comment(0)
R
0

Objective C

if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
    UIGraphicsBeginImageContextWithOptions(self.view.window.bounds.size, NO, [UIScreen mainScreen].scale);
} else {
    UIGraphicsBeginImageContext(self.view.window.bounds.size);
}
[self.view.window drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
Rewrite answered 3/4, 2020 at 10:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.