Last active
August 28, 2020 06:21
-
-
Save sakrist/3761227 to your computer and use it in GitHub Desktop.
Getting screenshot on iOS OpenGL ES
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (UIImage*) takePicture { | |
int s = 1; | |
UIScreen* screen = [UIScreen mainScreen]; | |
if ([screen respondsToSelector:@selector(scale)]) { | |
s = (int) [screen scale]; | |
} | |
GLint viewport[4]; | |
glGetIntegerv(GL_VIEWPORT, viewport); | |
int width = viewport[2]; | |
int height = viewport[3]; | |
int myDataLength = width * height * 4; | |
GLubyte *buffer = (GLubyte *) malloc(myDataLength); | |
GLubyte *buffer2 = (GLubyte *) malloc(myDataLength); | |
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer); | |
for(int y1 = 0; y1 < height; y1++) { | |
for(int x1 = 0; x1 <width * 4; x1++) { | |
buffer2[(height - 1 - y1) * width * 4 + x1] = buffer[y1 * 4 * width + x1]; | |
} | |
} | |
free(buffer); | |
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer2, myDataLength, releaseData); | |
int bitsPerComponent = 8; | |
int bitsPerPixel = 32; | |
int bytesPerRow = 4 * width; | |
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); | |
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault; | |
CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault; | |
CGImageRef imageRef = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent); | |
CGColorSpaceRelease(colorSpaceRef); | |
CGDataProviderRelease(provider); | |
UIImage *image = [ UIImage imageWithCGImage:imageRef scale:s orientation:UIImageOrientationUp ]; | |
return image; | |
} |
For ios 7+ one can use the following snippet:
UIGraphicsBeginImageContext(self.view.frame.size);
[self.view drawViewHierarchyInRect:self.view.frame afterScreenUpdates:YES];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
I also got a black image because glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer) fills buffer with zeroes
@namiazad Were you able to solve the issue? Even I am getting empty buffer
This works great.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@notedit It could because you need another settings for CGDataProvider or in glReadPixels, or even something else. Debug and check each setting/parameter. For @vikram123456 it works and for me too, so look in your code.