从GLPaint保存imageRef会创build完全黑色的图像

嗨,我正在尝试绘制应用程序,并有一个问题,当涉及到保存所绘制的图像。 现在我很早就学习这个,但我已经添加了代码: 如何从EAGLView获得UIImage? 保存绘制的图像。

我创build了一个新的应用程序,然后显示我创build的viewController。 在IB中,我添加了一个是PaintingView的视图,imageView位于它的后面。

到目前为止,我对绘画视图所做的唯一修改是将背景变为清晰,并将背景设置为清晰,以便我可以在其后显示图像。 绘图效果很好,我唯一的问题就是保存。

- (void)saveImageFromGLView:(UIView *)glView { if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) { /// This IS being activated with code 0 NSLog(@"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES)); } int s = 1; UIScreen* screen = [ UIScreen mainScreen ]; if ( [ screen respondsToSelector:@selector(scale) ] ) s = (int) [ screen scale ]; const int w = self.frame.size.width; const int h = self.frame.size.height; const NSInteger myDataLength = w * h * 4 * s * s; // allocate array and read pixels into it. GLubyte *buffer = (GLubyte *) malloc(myDataLength); glReadPixels(0, 0, w*s, h*s, GL_RGBA, GL_UNSIGNED_BYTE, buffer); // gl renders "upside down" so swap top to bottom into new array. // there's gotta be a better way, but this works. GLubyte *buffer2 = (GLubyte *) malloc(myDataLength); for(int y = 0; y < h*s; y++) { memcpy( buffer2 + (h*s - 1 - y) * w * 4 * s, buffer + (y * 4 * w * s), w * 4 * s ); } free(buffer); // work with the flipped buffer, so get rid of the original one. // make data provider with data. CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer2, myDataLength, NULL); // prep the ingredients int bitsPerComponent = 8; int bitsPerPixel = 32; int bytesPerRow = 4 * w * s; CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault; CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault; // make the cgimage CGImageRef imageRef = CGImageCreate(w*s, h*s, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent); // then make the uiimage from that UIImage *myImage = [ UIImage imageWithCGImage:imageRef scale:s orientation:UIImageOrientationUp ]; UIImageWriteToSavedPhotosAlbum( myImage, nil, nil, nil ); CGImageRelease( imageRef ); CGDataProviderRelease(provider); CGColorSpaceRelease(colorSpaceRef); free(buffer2); } 

将上面的代码添加到示例应用程序工作正常,问题是在我的新应用程序中。 唯一的区别是我可以告诉我没有包含PaintingWindow – 那会是问题吗?

就好像saveImage方法没有看到图纸的数据。

save方法应该在OpenGL上下文的范围内调用。 为了解决这个问题,你可以在同一个渲染文件中移动你的方法,并从外部调用这个函数。

你也需要考虑OpenGL清晰的颜色。

(详细的解释在评论中,哈哈)

我发现把CGBitmapInfo改成:

 CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast; 

结果在透明的背景下。

啊,你一开始就要这样做。

 [EAGLContext setCurrentContext:drawContext];