Capture a screen shot before a Share Extension's view appears - ios

I'm creating a share extension that currently captures web content via javascript, and a resulting NSDictionary [NSExtensionJavaScriptPreprocessingResultsKey]. That's all working great.
The next phase of my implementation is to get a screen shot of the web view of the page in Safari that the user is on.
Does anyone know if there's a pattern where taking a screen shot of the web page prior to the view that's loading w/the extension? Clearly viewWillAppear won't work, but I'll past the code I have none the less:
- (void)viewWillAppear:(BOOL)animated
{
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0);
[self.view drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:YES];
UIImage *screenShotImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.imageView.image = screenShotImage;
[super viewWillAppear:animated];
}

Related

How to get a screenshot of a CATiledLayer based TilingView

I'm trying in my app to take a screenshot of the current screen contents, where my TilingView (based on CATiledLayers) displays a number of transparent large tiled images.
Also I added some subViews to the TilingView, which are magically captured in the screenshot, however the underlying contents of the TilingView is not captured!??
The following code-snippets takes a snapshot of the visible screen, which seems to work well for a NON CATiledLayer based view-hierarchy, but unfortunately doesn't work for my setup. Even if I pass the topmost superview of the TilingView (being the actual UIViewController.view), I see only in my snapshot the StatusBar, NavigationBar, the TilingViews subViews and the TabBar, but again NOT the TilingViews contents.
- (UIImage*)captureView:(UIView *)viewToCapture {
CGRect rect = [[UIScreen mainScreen] bounds];
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[viewToCapture.layer renderInContext:context];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
Does anybody know or see here what I'm missing? Do I need to delve deeper into the CG-related display stack with some, for me, unknown CG-API calls? Thanks in advance.
By searching some more in StackOverflow I've found code which seems to do what I wanted. Basically I need to change the above method into:
- (UIImage*)captureView:(UIView*)viewToCapture {
UIGraphicsBeginImageContextWithOptions(viewToCapture.bounds.size, NO, [UIScreen mainScreen].scale);
[viewToCapture drawViewHierarchyInRect:viewToCapture.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
Thanks go to the question/answer at: How to get a screenshot of a view containing GPUImageView?

Blurring a UIView that contains the keyboard with content beneath it (iOS 7)

I have a UIView with a UITableView the extends beneath the keyboard. The content in the table view is bright enough, making it clear that content sits behind the keyboard. I'm attempting to take a screenshot of the entire view in order to blur it using the following code:
- (UIImage *)screenshotFromView:(UIView *)view;
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0.0);
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
However, the image that is returned does not create a transparent keyboard. This presents an odd transition when going from the non-blurred view to the blurred view, since there is clearly content behind the keyboard before the transition to the blurred image.
Is it possible to take a screenshot of the entire screen, without use of private APIs, while still keeping the transparency of the keyboard + the status bar?
I got the exact problem as you these days, so I exactly know what you want. I wanted the whole UI blurred behind a message including the keyboard, which is not included with any regular screenshot method. My cure is the following code:
- (UIImage*)screenShotWithKeyboard:(UIView *)viewToShoot
{
UIWindow *keyboard = nil;
for (UIWindow *window in [[UIApplication sharedApplication] windows])
{
if ([[window description] hasPrefix:#"<UITextEffectsWin"])
{
keyboard = window;
break;
}
}
// Define the dimensions of the screenshot you want to take (the entire screen in this case)
CGSize size = [[UIScreen mainScreen] bounds].size;
// Create the screenshot
UIGraphicsBeginImageContext(size);
CGContextRef context=UIGraphicsGetCurrentContext();
// delete following line if you only want the keyboard
[[viewToShoot layer] renderInContext:context];
if(keyboard!=nil)
[[keyboard layer] renderInContext:context];
UIImage *screenImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return screenImg;
}
I got the idea from an article of Aran Balkan I broke it down to one method and testet it for iOS 7 which seems to work for me. The article worth reading as he explain the tricks behind a little. As you only want the actual keyboard as image, you can comment out the line I marked in the code. With that image keyboard you can do your blur stuff yourself.
The code is far from perfect, but I think you got the idea.
Two thinks at the end:
I am a freshman to objective c and iOS development. If you find any problematic bugs, a comment is very welcome to improve this answer.
Second, I wrote this code today in my app and I do not know yet if I violate any developer rules for iOS. At the moment I do not see any problems, but I will investigate this further as I want to release my app with that graphic trick. I will keeping this post updated. Until than, as with point one, I would highly appreciate any comment regarding this issue.
Have you considered using UIKeyboardAppearanceDark? Currently the default value of keyboardAppearance corresponds to UIKeyboardAppearanceLight, so it may not be suited to your use case.

Why does my programmatically created screenshot look so bad on iOS 7?

I am trying to implement sharing app with facebook.
I used this code to take the screenshot:
CGSize imageSize = CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height);
UIGraphicsBeginImageContext(imageSize);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
It works great on iOS 6, but in iOS 7 the image looks very bad.
I used this answer: iOS: what's the fastest, most performant way to make a screenshot programmatically?
for trying to fix it, and it helped, still the screenshot looks bad.
The screen gets another color, and some objects (like labels) aren't showing on the image taken.
Any help?
----Update----
I managed to solve the most objects, by change them to retain instead of weak. My main problem remained my tableview, that shown as a big white block (It supposed to be transparent, with labels with white text, so all we see is white cells). I did try to define the table background as clearcolor,not helps..
----Last Update---
There are wonderful answers here that not really regarding to my issue.. I wanted to make it work on device that runs with iOS7 but without using iOS7 SDK, since it takes to much effort to switch the project SDK in this point, when the project is almost done.
Anyway, I added the peace of code that finally solved my issue:
This change simply solve the problem:
UIGraphicsBeginImageContextWithOptions(imageSize, NO , 0.0f);
instead of:
UIGraphicsBeginImageContext(imageSize);
New API has been added since iOS 7, that should provide efficient way of getting snapshot
snapshotViewAfterScreenUpdates: renders the view into a UIView with unmodifiable content
resizableSnapshotViewFromRect:afterScreenUpdates:withCapInsets : same thing, but with resizable insets
drawViewHierarchyInRect:afterScreenUpdates: : same thing if you need all subviews to be drawn too (like labels, buttons...)
You can use the UIView returned for any UI effect, or render in into an image like you did if you need to export.
I don't know how good this new method performs VS the one you provided (although I remember Apple engineers saying this new API was more efficient)
you can try this
- (UIImage *) screenshot {
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale);
[self.view drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
in iOS 8 : this is how i am doing to get ScreenShot
just added one UIImageView and Method to take screenshot in .h file
#property (weak, nonatomic) IBOutlet UIImageView *imageView;
-(IBAction)takeSnapShot:(id)sender;
2 added code snip for taking screen shot and set on UIImageView in .m file
- (IBAction)takeSnapShot:(id)sender
{
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *snapShotImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
imageView.image = snapShotImage;
}
below is the output i got.
On iOS7 you can have glitches if you use
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES]
during ongoing animation. Set afterScreenUpdates = NO to get rid of glitches.
Make sure that opaque is set to NO

Blur screen with iOS 7's snapshot API

I believe the NDA is down, so I can ask this question. I have a UIView subclass:
BlurView *blurredView = ((BlurView *)[self.view snapshotViewAfterScreenUpdates:NO]);
blurredView.frame = self.view.frame;
[self.view addSubview:blurredView];
It does its job so far in capturing the screen, but now I want to blur that view. How exactly do I go about this? From what I've read I need to capture the current contents of the view (context?!) and convert it to CIImage (no?) and then apply a CIGaussianBlur to it and draw it back on the view.
How exactly do I do that?
P.S. The view is not animated, so it should be OK performance wise.
EDIT: Here is what I have so far. The problem is that I can't capture the snapshot to a UIImage, I get a black screen. But if I add the view as a subview directly, I can see the snapshot is there.
// Snapshot
UIView *view = [self.view snapshotViewAfterScreenUpdates:NO];
// Convert to UIImage
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Apply the UIImage to a UIImageView
BlurView *blurredView = [[BlurView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)];
[self.view addSubview:blurredView];
blurredView.imageView.image = img;
// Black screen -.-
BlurView.m:
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.imageView = [[UIImageView alloc] init];
self.imageView.frame = CGRectMake(20, 20, 200, 200);
[self addSubview:self.imageView];
}
return self;
}
Half of this question didn't get answered, so I thought it worth adding.
The problem with UIScreen's
- (UIView *)snapshotViewAfterScreenUpdates:(BOOL)afterUpdates
and UIView's
- (UIView *)resizableSnapshotViewFromRect:(CGRect)rect
afterScreenUpdates:(BOOL)afterUpdates
withCapInsets:(UIEdgeInsets)capInsets
Is that you can't derive a UIImage from them - the 'black screen' problem.
In iOS7 Apple provides a third piece of API for extracting UIImages, a method on UIView
- (BOOL)drawViewHierarchyInRect:(CGRect)rect
afterScreenUpdates:(BOOL)afterUpdates
It is not as fast as snapshotView, but not bad compared to renderInContext (in the example provided by Apple it is five times faster than renderInContext and three times slower than snapshotView)
Example use:
UIGraphicsBeginImageContextWithOptions(image.size, NULL, 0);
[view drawViewHierarchyInRect:rect];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Then to get a blurred version
UIImage* lightImage = [newImage applyLightEffect];
where applyLightEffect is one of those Blur category methods on Apple's UIImage+ImageEffects category mentioned in the accepted answer (the enticing link to this code sample in the accepted answer doesn't work, but this one will get you to the right page: the file you want is iOS_UIImageEffects).
The main reference is to WWDC2013 session 226, Implementing Engaging UI on iOS
By the way, there is an intriguing note in Apple's reference docs for renderInContext that hints at the black screen problem..
Important: The OS X v10.5 implementation of this method does not support the entire Core Animation composition model. QCCompositionLayer, CAOpenGLLayer, and QTMovieLayer layers are not rendered. Additionally, layers that use 3D transforms are not rendered, nor are layers that specify backgroundFilters, filters, compositingFilter, or a mask values. Future versions of OS X may add support for rendering these layers and properties.
The note hasn't been updated since 10.5, so I guess 'future versions' may still be a while off, and we can add our new CASnapshotLayer (or whatever) to the list.
Sample Code from WWDC ios_uiimageeffects
There is a UIImage category named UIImage+ImageEffects
Here is its API:
- (UIImage *)applyLightEffect;
- (UIImage *)applyExtraLightEffect;
- (UIImage *)applyDarkEffect;
- (UIImage *)applyTintEffectWithColor:(UIColor *)tintColor;
- (UIImage *)applyBlurWithRadius:(CGFloat)blurRadius
tintColor:(UIColor *)tintColor
saturationDeltaFactor:(CGFloat)saturationDeltaFactor
maskImage:(UIImage *)maskImage;
For legal reason I can't show the implementation here, there is a demo project in it. should be pretty easy to get start with.
To summarize how to do this with foundry's sample code, use the following:
I wanted to blur the entire screen just slightly so for my purposes so I'll use the main screen bounds.
CGRect screenCaptureRect = [UIScreen mainScreen].bounds;
UIView *viewWhereYouWantToScreenCapture = [[UIApplication sharedApplication] keyWindow];
//screen capture code
UIGraphicsBeginImageContextWithOptions(screenCaptureRect.size, NO, [UIScreen mainScreen].scale);
[viewWhereYouWantToScreenCapture drawViewHierarchyInRect:screenCaptureRect afterScreenUpdates:NO];
UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//blur code
UIColor *tintColor = [UIColor colorWithWhite:1.0 alpha:0];
UIImage *blurredImage = [capturedImage applyBlurWithRadius:1.5 tintColor:tintColor saturationDeltaFactor:1.2 maskImage:nil];
//or use [capturedImage applyLightAffect] but I thought that was too much for me
//use blurredImage in whatever way you so desire!
Notes on the screen capture part
UIGraphicsBeginImageContextWithOptions() 2nd argument is opacity. It should be NO unless you have nothing with any alpha other than 1. If you return yes the screen capture will not look at transparency values so it will go faster but will probably be wrong.
UIGraphicsBeginImageContextWithOptions() 3rd argument is the scale. Probably want to put in the scale of the device like I did to make sure and differentiate between retina and non-retina. But I haven't really tested this and I think 0.0f also works.
drawViewHierarchyInRect:afterScreenUpdates: watch out what you return for the screen updates BOOL. I tried to do this right before backgrounding and if I didn't put NO the app would go crazy with glitches when I returned to the foreground. You might be able to get away with YES though if you're not leaving the app.
Notes on blurring
I have a very light blur here. Changing the blurRadius will make it blurrier, and you can change the tint color and alpha to make all sorts of other effects.
Also you need to add a category for the blur methods to work...
How to add the UIImage+ImageEffects category
You need to download the category UIImage+ImageEffects for the blur to work. Download it here after logging in: https://developer.apple.com/downloads/index.action?name=WWDC%202013
Search for "UIImageEffects" and you'll find it. Just pull out the 2 necessary files and add them to your project. UIImage+ImageEffects.h and UIImage+ImageEffects.m.
Also, I had to Enable Modules in my build settings because I had a project that wasn't created with xCode 5. To do this go to your target build settings and search for "modules" and make sure that "Enable Modules" and "Link Frameworks Automatically" are both set to yes or you'll have compiler errors with the new category.
Good luck blurring!
Check WWDC 2013 sample application "running with a snap".
The blurring is there implemented as a category.

ScreenShot of an UIWebView that is not currently on screen

I'm trying to generate thumbnails of several pages that will be displayed through a UIWebView. The problem is all of the images come out as gray or as the background color I set for the UIWebView. Could it be that I am not allowing the web view enough time to load the page?
I believe I want to do the following:
Create a UIWebView that is not visible on the screen
Setup graphics context
For each page:
Call loadRequest on the web view
Render web view in graphics context
capture screenshot
End graphic context
Here is the code I have for a single image:
UIWebView *screenWebView = _screenshotWebView;
UIView *screenView = _screenshotView;
if ([UIScreen instancesRespondToSelector:#selector(scale)] && [[UIScreen mainScreen] scale] == 2.0f) {
UIGraphicsBeginImageContextWithOptions(screenView.bounds.size, NO, 2.0f);
} else {
UIGraphicsBeginImageContext(screenView.bounds.size);
}
[screenWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:path ofType:#"html"]isDirectory:NO]]];
[screenView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
I defined _screenshotWebView and _screenshotView within a XIB file because I thought I may not have been initializing them correctly.
Any thoughts? Thanks!
Edit: Here is some code that implements this functionality in case someone else needs it: https://github.com/rmcl/webview_screenshot
As you theorized, there isn't time for the UIWebView to load the page. That method will asynchronously start the page load; the UIWebView probably won't get a chance to do any work until you've returned to the run loop.
Try implementing webViewDidFinishLoad: and do your rendering after it has completed.

Resources