简体   繁体   English

以编程方式获取结合OpenGL和UIKit元素的屏幕截图

[英]Programmatically take a screenshot combining OpenGL and UIKit elements

I was wondering if anyone could provide an example of how to take a screenshot which mixes OpenGL and UIKit elements. 我想知道是否有人可以提供如何拍摄混合OpenGL和UIKit元素的屏幕截图的示例。 Ever since Apple made UIGetScreenImage() private this has become a pretty difficult task because the two common methods Apple used to replace it capture only UIKit or only OpenGL. 自从Apple将UIGetScreenImage()私有化后,这已成为一项相当困难的任务,因为Apple用来取代它的两种常用方法只捕获UIKit或仅捕获OpenGL。

This similar question references Apple's Technical Q&A QA1714 , but the QA only describes how to handle elements from the camera and UIKit. 这个类似的问题引用了Apple的技术问答QA1714 ,但QA仅描述了如何处理来自相机和UIKit的元素。 How do you go about rendering the UIKit view hierarchy into an image context and then drawing the image of your OpenGL ES view on top of it like the answer to the similar question suggests? 你如何将UIKit视图层次结构渲染到图像上下文中,然后在其上绘制OpenGL ES视图的图像,就像类似问题的答案所示?

This should do the trick. 这应该可以解决问题。 Basically rendering everything to CG and creating an image you can do whatever with. 基本上将所有内容渲染为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;
}

Then, to create a screenshot 然后,创建一个截图

UIImage *glImage = [self drawGlToImage];
UIImage *screenshot = [self createSavableImage:glImage];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM