保存屏幕截图时从层次结构中删除顶视图

时间:2013-03-01 21:59:13

标签: iphone ios uiimage core-graphics calayer

我正在使用一种方法来获取UIImage截图以编程方式,这非常有效。我现在要做的是删除屏幕截图中包含的最顶级的UIView 不要将其从屏幕上的实际视图中删除,因此只需设置topView.hidden = YES即可。我正在使用此方法保存屏幕截图:

- (UIImage*)screenshot
{
CGSize imageSize = [[UIScreen mainScreen] bounds].size;
if (NULL != UIGraphicsBeginImageContextWithOptions)
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
else
    UIGraphicsBeginImageContext(imageSize);

CGContextRef context = UIGraphicsGetCurrentContext();

// Iterate over every window from back to front
for (UIWindow *window in [[UIApplication sharedApplication] windows])
{
    if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen])
    {
        // -renderInContext: renders in the coordinate space of the layer,
        // so we must first apply the layer's geometry to the graphics context
        CGContextSaveGState(context);
        // Center the context around the window's anchor point
        CGContextTranslateCTM(context, [window center].x, [window center].y);
        // Apply the window's transform about the anchor point
        CGContextConcatCTM(context, [window transform]);
        // Offset by the portion of the bounds left of and above the anchor point
        CGContextTranslateCTM(context,
                              -[window bounds].size.width * [[window layer] anchorPoint].x,
                              -[window bounds].size.height * [[window layer] anchorPoint].y);

        // Render the layer hierarchy to the current context
        [[window layer] renderInContext:context];

        // Restore the context
        CGContextRestoreGState(context);
    }
}

// Retrieve the screenshot image
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return image;
}

我的第一个想法是从超级层中删除子层:

NSArray *sublayers = [[window layer] sublayers];
[[window layer] replaceSublayer:[sublayers objectAtIndex:[sublayers count] - 1] with:nil];

但我发现sublayers数组只有一个对象。如何从屏幕截图中删除顶视图?

1 个答案:

答案 0 :(得分:0)

例如,您在视图层次结构中有View1,并且您不想截取View1的屏幕截图,那么您可以执行View1.hiden = TRUE;在截图之前你可以做View1.hiden = FALSE;截图后。

可能会对你有帮助。