捕获UIView的UIImage,包括UINavigationBar

时间:2012-01-22 11:41:38

标签: ios animation uiview uiimage uinavigationbar

我发现这段代码很不错:

+ (UIImage *) imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, [[UIScreen mainScreen] scale]); 
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

但我也需要捕获UINavigationBar,因为我想在我的UIStoryboardSegue中将图像用作过渡层。有什么想法吗?

4 个答案:

答案 0 :(得分:7)

使用视图窗口作为视图,因此也会包含导航栏和状态栏。如果您需要删除状态栏,则必须裁剪图像。

答案 1 :(得分:3)

你应该截取self.navigationController?.view的截图。 这样你就可以使用navigationBar获得整个视图但没有状态栏。

if let view = self.navigationController?.view {
    let snapshot = view.snapshotViewAfterScreenUpdates(false)
}

答案 2 :(得分:2)

而不是view.layer给appdelegate.window.layer的引用它将起作用。

答案 3 :(得分:0)

哇,这些答案真的没有用。这就是你如何获得包括导航控制器在内的所有内容的截图

-(void) takeScreenshot
{

    CGRect screenRect = [[UIScreen mainScreen] bounds];
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
    {
        //its iphone


        CGSize result = [[UIScreen mainScreen] bounds].size;
        if(result.height == 480 || result.width == 480)
        {
            // iPhone Classic
            screenRect  = CGRectMake(0, 0, 320, 480);
        }
        if(result.height == 568 || result.width == 568)
        {
            // iPhone 5
            screenRect  = CGRectMake(0, 0, 320, 568);
        }
    }
    else
    {
        //its pad
        screenRect  = CGRectMake(0, 0, 768, 1024);
    }

    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];

    // This code is for high resolution screenshot
    UIGraphicsBeginImageContextWithOptions(screenRect.size, NO, 0.0);

    //this was pre iOS 7.0
    //[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];

    // iOS 7.x -->
    [[[[UIApplication sharedApplication] windows] objectAtIndex:0] drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:YES]; // Set To YES

    UIImage *viewImage2 = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();


    NSData* imageData2 = UIImageJPEGRepresentation(viewImage2, 1.0);
    NSString* incrementedImgStr2 = [NSString stringWithFormat: @"UserScreenShotPic.jpg"];


    // Now we get the full path to the file
    NSString* fullPathToFile3 = [documentsDirectory stringByAppendingPathComponent:incrementedImgStr2];
    [imageData2 writeToFile:fullPathToFile3 atomically:NO];

}