gpt4 book ai didi

iOS 屏幕截图失败,使用 OpenGL

转载 作者:行者123 更新时间:2023-11-29 00:41:22 25 4
gpt4 key购买 nike

这是我的代码:

@implementation UIView (LCExtension)

- (UIImage *)screenshotWithRect:(CGRect)rect {

UIGraphicsBeginImageContext(self.bounds.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
image = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(image.CGImage, rect)];
UIGraphicsEndImageContext();
return image;
}

@end

我在这里设置了一个断点:

code

运行:

  • 这是view-self:(来自 OpenGL 渲染的图片)

    view-self

  • 这是生成的图片:

    image

为什么是黑图?

最佳答案

当使用 OpenGL (ES) 时,是的,我假设您正在使用 OpenGL ES,因为您有一个 UIView 类别,请记住在呈现渲染缓冲区之前捕获屏幕。一旦您或 GLKViewController 的子类呈现渲染缓冲区,它就变成了前帧缓冲区,然后屏幕帧缓冲区变成了后帧缓冲区,除了您使用 glClearColor 设置的颜色之外,它什么也没有给您。

[EAGLContext presentRenderbuffer:]

这里是截屏的示例代码。

- (UIImage *)createImageFromFramebuffer {
GLint params[10];
glGetIntegerv(GL_VIEWPORT, params);
int width = params[2];
int height = params[3];
const int renderTargetWidth = width;
const int renderTargetHeight = height;
const int renderTargetSize = renderTargetWidth*renderTargetHeight * 4;

uint8_t* imageBuffer = (uint8_t*)malloc(renderTargetSize);
glReadPixels(params[0], params[1],
renderTargetWidth, renderTargetHeight,
GL_RGBA, GL_UNSIGNED_BYTE, imageBuffer);

const int rowSize = renderTargetWidth*4;

CGDataProviderRef ref = CGDataProviderCreateWithData(NULL, imageBuffer, renderTargetSize, NULL);
CGImageRef iref = CGImageCreate(renderTargetWidth, renderTargetHeight, 8, 32, rowSize,
CGColorSpaceCreateDeviceRGB(),
kCGImageAlphaLast | kCGBitmapByteOrderDefault, ref,
NULL, true, kCGRenderingIntentDefault);

uint8_t* contextBuffer = (uint8_t*)malloc(renderTargetSize);
memset(contextBuffer, 0, renderTargetSize);
CGContextRef context = CGBitmapContextCreate(contextBuffer, renderTargetWidth, renderTargetHeight, 8, rowSize,
CGImageGetColorSpace(iref),
kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big);
CGContextTranslateCTM(context, 0.0, renderTargetHeight);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, CGRectMake(0.0, 0.0, renderTargetWidth, renderTargetHeight), iref);
CGImageRef outputRef = CGBitmapContextCreateImage(context);

UIImage* image = [[UIImage alloc] initWithCGImage:outputRef];

CGImageRelease(outputRef);
CGContextRelease(context);
CGImageRelease(iref);
CGDataProviderRelease(ref);

free(contextBuffer);
free(imageBuffer);
return image;
}

关于iOS 屏幕截图失败,使用 OpenGL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39405433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com