5

我想知道是否有人可以提供一个示例,说明如何截取混合 OpenGL 和 UIKit 元素的屏幕截图。自从 Apple 将UIGetScreenImage()其私有化以来,这已成为一项相当困难的任务,因为 Apple 用来替换它的两种常用方法仅捕获 UIKit 或仅捕获 OpenGL。

这个类似的问题引用了Apple 的 Technical Q&A QA1714,但 QA 仅描述了如何处理来自相机和 UIKit 的元素。您如何将 UIKit 视图层次结构渲染到图像上下文中,然后在其上绘制 OpenGL ES 视图的图像,就像类似问题的答案所暗示的那样?

4

1 回答 1

4

这应该可以解决问题。基本上将所有内容渲染到 CG 并创建一个你可以做任何事情的图像。

// In Your UI View Controller

- (UIImage *)createSavableImage:(UIImage *)plainGLImage
{    
    UIImageView *glImage = [[UIImageView alloc] initWithImage:[myGlView drawGlToImage]];
    glImage.transform = CGAffineTransformMakeScale(1, -1);

    UIGraphicsBeginImageContext(self.view.bounds.size);

    //order of getting the context depends on what should be rendered first.
    // this draws the UIKit on top of the gl image
    [glImage.layer renderInContext:UIGraphicsGetCurrentContext()];
    [someUIView.layer renderInContext:UIGraphicsGetCurrentContext()];

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

    // Do something with resulting image 
    return finalImage;
}

// In Your GL View

- (UIImage *)drawGlToImage
{
    // Draw OpenGL data to an image context 

    UIGraphicsBeginImageContext(self.frame.size);

    unsigned char buffer[320 * 480 * 4];

    CGContextRef aContext = UIGraphicsGetCurrentContext();

    glReadPixels(0, 0, 320, 480, GL_RGBA, GL_UNSIGNED_BYTE, &buffer);

    CGDataProviderRef ref = CGDataProviderCreateWithData(NULL, &buffer, 320 * 480 * 4, NULL);

    CGImageRef iref = CGImageCreate(320,480,8,32,320*4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaLast, ref, NULL, true, kCGRenderingIntentDefault);

    CGContextScaleCTM(aContext, 1.0, -1.0);
    CGContextTranslateCTM(aContext, 0, -self.frame.size.height);

    UIImage *im = [[UIImage alloc] initWithCGImage:iref];

    UIGraphicsEndImageContext();

    return im;
}

然后,创建一个屏幕截图

UIImage *glImage = [self drawGlToImage];
UIImage *screenshot = [self createSavableImage:glImage];
于 2012-07-02T19:43:52.243 回答