opengl层截图中的问题

时间:2010-12-18 05:09:41

标签: ipad

我正在使用以下代码拍摄我的cocos2D iPad应用程序的屏幕截图。

 CGSize size = CGSizeMake(WIDTH,HEIGHT);
 //Create un buffer for pixels
 GLuint bufferLenght=size.width*size.height*4;
 GLubyte *buffer = (GLubyte *) malloc(bufferLenght);

 //Read Pixels from OpenGL
 glReadPixels(0,0,size.width,size.height,GL_RGBA,GL_UNSIGNED_BYTE,buffer);
 //Make data provider with data.
 CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer, bufferLenght, NULL);

 //Configure image
    int bitsPerComponent = 8;
    int bitsPerPixel = 32;
    int bytesPerRow = 4 * size.width;
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
    CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
 CGImageRef iref = CGImageCreate(size.width,size.height,bitsPerComponent,bitsPerPixel,bytesPerRow,colorSpaceRef,bitmapInfo,provider,NULL,NO,renderingIntent);

 uint32_t *pixels = (uint32_t *)malloc(bufferLenght);
 CGContextRef context = CGBitmapContextCreate(pixels, WIDTH, HEIGHT, 8, WIDTH*4, CGImageGetColorSpace(iref), kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

 CGContextTranslateCTM(context,0, size.height);
 CGContextScaleCTM(context, 1.0, -1.0);

 //screen shot of cocos2D layer
 CGContextDrawImage(context, CGRectMake(0.0, 0.0, size.width, size.height), iref);
 UIImage* screenshot = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context)];


 @try
 {
  NSFileManager *fileManager = [NSFileManager defaultManager]; 
  NSArray *documentsDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES); 
  NSString *paths = [documentsDir objectAtIndex:0]; 
  NSData *myData = UIImageJPEGRepresentation(screenshot, 1.0);
  NSDictionary *fileAttributes = [fileManager fileAttributesAtPath:paths traverseLink:YES];
  [fileManager createFileAtPath:[paths stringByAppendingPathComponent:@"design.jpg"] contents:myData attributes:fileAttributes];  
  UIImageWriteToSavedPhotosAlbum(screenshot, nil, nil, nil);

 }
 @catch (NSException *e) 
 {
  //NSLog(@"File error.....");
 }

 UIGraphicsEndImageContext();

 //Dealloc
 CGDataProviderRelease(provider);
 CGImageRelease(iref);
 CGContextRelease(context);
 free(buffer);
 free(pixels);

此代码在模拟器上正在使用,但不适用于实际设备。

请帮忙。

感谢。

1 个答案:

答案 0 :(得分:0)

完成了。问题在于我的opengl层的宽度。它的宽度必须是32的倍数,这不是我的情况。