这个方法忘了从哪里抄来的了,但非常好用。要实现保存当前屏幕显示之类的功能时,一个方法调用就搞定。
不说废话,贴代码:
02.
{
03.
CGSize displaySize = [[CCDirector sharedDirector] displaySizeInPixels];
04.
CGSize winSize = [[CCDirector sharedDirector] winSizeInPixels];
05.
06.
//Create buffer for pixels
07.
GLuint bufferLength = displaySize.width * displaySize.height * 4;
08.
GLubyte* buffer = (GLubyte*)
malloc
(bufferLength);
09.
10.
//Read Pixels from OpenGL
11.
glReadPixels(0, 0, displaySize.width, displaySize.height, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
12.
//Make data provider with data.
13.
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer, bufferLength, NULL);
14.
15.
//Configure image
16.
int
bitsPerComponent = 8;
17.
int
bitsPerPixel = 32;
18.
int
bytesPerRow = 4 * displaySize.width;
19.
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
20.
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
21.
CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
22.
CGImageRef iref = CGImageCreate(displaySize.width, displaySize.height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);
23.
24.
uint32_t* pixels = (uint32_t*)
malloc
(bufferLength);
25.
CGContextRef context = CGBitmapContextCreate(pixels, winSize.width, winSize.height, 8, winSize.width * 4, CGImageGetColorSpace(iref), kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
26.
27.
CGContextTranslateCTM(context, 0, displaySize.height);
28.
CGContextScaleCTM(context, 1.0f, -1.0f);
29.
30.
switch
([CCDirector sharedDirector].deviceOrientation)
31.
{
32.
case
CCDeviceOrientationPortrait:
break
;
33.
case
CCDeviceOrientationPortraitUpsideDown:
34.
CGContextRotateCTM(context, CC_DEGREES_TO_RADIANS(180));
35.
CGContextTranslateCTM(context, -displaySize.width, -displaySize.height);
36.
break
;
37.
case
CCDeviceOrientationLandscapeLeft:
38.
CGContextRotateCTM(context, CC_DEGREES_TO_RADIANS(-90));
39.
CGContextTranslateCTM(context, -displaySize.height, 0);
40.
break
;
41.
case
CCDeviceOrientationLandscapeRight:
42.
CGContextRotateCTM(context, CC_DEGREES_TO_RADIANS(90));
43.
CGContextTranslateCTM(context, displaySize.height-displaySize.width, -displaySize.height);
44.
break
;
45.
}
46.
47.
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, displaySize.width, displaySize.height), iref);
48.
CGImageRef imageRef = CGBitmapContextCreateImage(context);
49.
UIImage *outputImage = [[[UIImage alloc] initWithCGImage:imageRef] autorelease];
50.
51.
//Dealloc
52.
CGImageRelease(imageRef);
53.
CGDataProviderRelease(provider);
54.
CGImageRelease(iref);
55.
CGColorSpaceRelease(colorSpaceRef);
56.
CGContextRelease(context);
57.
free
(buffer);
58.
free
(pixels);
59.
60.
return
outputImage;
61.
}
这个方法返回 UIImage 对象,因此保存为文件,或者构造为材质都可以。