使用编程方式结合OpenGL和UIKit元素进行屏幕截图

6
我想知道是否有人能提供一个混合使用OpenGL和UIKit元素的截图示例。自从苹果将UIGetScreenImage()设为私有后,这变成了一项相当困难的任务,因为苹果用来替代它的两种常见方法只捕获UIKit或OpenGL中的内容。 这个类似的问题参考了苹果的技术问答QA1714,但该问答仅介绍了如何处理摄像机和UIKit的元素。你如何渲染UIKit视图层次结构到图像上下文中,并在其上绘制你的OpenGL ES视图的图像,就像类似问题的答案所建议的那样?

或者,有没有适合替代UIGetScreenImage的东西可以同时处理这两个事情? - Austin
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];

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