捕获包括UINavigationBar的UIView的UIImage

8
我找到了这段代码,非常不错:
+ (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个回答

7

将视图的窗口作为视图以便包括导航栏和状态栏。如果需要移除状态栏,您需要裁剪图片。


我该如何在推出视图控制器之前截取包括导航栏在内的视图控制器?我需要全屏截取目标视图控制器。 - cschuff
如果您有指向视图控制器的指针,即使它尚未被推送,您也可以轻松访问该视图控制器的视图。 - Fabian Kreiser
是的,但是1.导航栏不属于视图吗?2.在它被推出之前我不能访问它的NavigationBar吗?VC2中导航栏的外观与VC1不同。 - cschuff
如果想要在截图中包含导航栏或导航控制器视图,您需要访问视图的窗口。如果它没有被推送,并且您想要包含导航栏,则必须在截图之前将其推入。 - Fabian Kreiser

4
你应该拍摄self.navigationController?.view的屏幕截图。 这样,你就能得到包含navigationBar但不包含状态栏的整个视图。
if let view = self.navigationController?.view {
    let snapshot = view.snapshotViewAfterScreenUpdates(false)
}

2

不要使用view.layer,而是使用appdelegate.window.layer的引用,这样就能正常工作。


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];

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接