Skip to content

Instantly share code, notes, and snippets.

@evadne
Created December 24, 2011 17:37
Show Gist options
  • Save evadne/1517894 to your computer and use it in GitHub Desktop.
Save evadne/1517894 to your computer and use it in GitHub Desktop.
Capturing Default iOS Keyboard Rect & Image
anImageView.image = ((^ (CGRect *outKeyboardRect){
[CATransaction begin];
UIWindow *tempWindow = [[[UIWindow alloc] initWithFrame:[UIScreen mainScreen].applicationFrame] autorelease];
[tempWindow makeKeyAndVisible];
UITextField *fauxTextField = [[[UITextField alloc] initWithFrame:(CGRect){ 0, 0, 128, 128 }] autorelease];
[tempWindow addSubview:fauxTextField];
fauxTextField.alpha = 0;
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
__block NSNotification *nrKeyboardDidShowNotification = nil;
__block id nrKeyboardDidShowNotificationListener = [center addObserverForName:UIKeyboardDidShowNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
nrKeyboardDidShowNotification = [note retain];
[center removeObserver:nrKeyboardDidShowNotificationListener];
}];
[fauxTextField becomeFirstResponder];
UIScreen *mainScreen = [UIScreen mainScreen];
UIGraphicsBeginImageContextWithOptions(mainScreen.bounds.size, YES, mainScreen.scale);
CGContextRef context = UIGraphicsGetCurrentContext();
for (UIWindow *aWindow in [UIApplication sharedApplication].windows)
if (aWindow.screen == mainScreen)
if (aWindow != tempWindow)
[aWindow.layer renderInContext:context];
UIImage *fullScreenImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[fauxTextField resignFirstResponder];
[fauxTextField removeFromSuperview];
[CATransaction commit];
[nrKeyboardDidShowNotification autorelease];
if (!nrKeyboardDidShowNotification)
return nil;
NSValue *keyboardRectValue = [[nrKeyboardDidShowNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
if (!keyboardRectValue)
return nil;
CGRect keyboardRect = [keyboardRectValue CGRectValue];
CGImageRef fullScreenImageRef = fullScreenImage.CGImage;
CGRect (^scaledRect)(CGRect, CGFloat) = ^ (CGRect aRect, CGFloat scale) {
return (CGRect) {
aRect.origin.x * scale,
aRect.origin.y * scale,
aRect.size.width * scale,
aRect.size.height * scale
};
};
CGRect scaledKeyboardRect = scaledRect(keyboardRect, mainScreen.scale);
CGImageRef keyboardImageRef = CGImageCreateWithImageInRect(fullScreenImageRef, scaledKeyboardRect);
if (!keyboardImageRef)
return nil;
UIImage *keyboardImage = [UIImage imageWithCGImage:keyboardImageRef scale:mainScreen.scale orientation:UIImageOrientationUp];
CGImageRelease(keyboardImageRef);
if (outKeyboardRect)
*outKeyboardRect = keyboardRect;
return keyboardImage;
})(&keyboardRect));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment