iOS捕获相机控制器的“屏幕截图”

时间:2012-01-25 00:59:41

标签: objective-c ios camera screenshot avcapturesession

在我的应用程序中,我显示相机,我正在使用UIGetScreenImage截取某些perts的截图,(我尝试了UIGraphicsGetImageFromCurrentImageContext,它适用于我的应用程序的几乎任何部分的截图,但对于相机视图,它只会返回一个空白的白色图片)...无论如何,我担心Apple会因为UIGetScreenImage拒绝我的应用程序...如何在不使用此方法的情况下从相机的左上角拍摄50px x 50px的“截图”?我搜索过,所有我能找到的是“AVCaptureSession”,我找不到更多关于它的作用,或者它是否甚至是我正在寻找的......有什么见解? :)谢谢你们!

2 个答案:

答案 0 :(得分:3)

它没有比Apple how to capture the camera's view上的文档更清晰。是的,这确实涉及班级AVCaptureSession

如果您确实需要界面的屏幕截图,则应该使用docs for that。从链接中剪切并粘贴代码(如果这不起作用,您应该向Apple提交错误报告):

更新:似乎在较新版本的iOS上不再支持此方法。第二个链接现在也被打破了。

- (UIImage*)screenshot 
{
    // Create a graphics context with the target size
    // On iOS 4 and later, use UIGraphicsBeginImageContextWithOptions to take the scale into consideration
    // On iOS prior to 4, fall back to use UIGraphicsBeginImageContext
    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;
}

答案 1 :(得分:-1)

从iOS7开始,您可以使用:

  

drawViewHierarchyInRect

UIImage *image;
UIGraphicsBeginImageContext(self.view.frame.size);
[self.view drawViewHierarchyInRect:self.view.frame afterScreenUpdates:YES];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();