一般的螢幕截圖方法在面對 OpenGL 場景時會失效——擷取到的資料是空的。這是因為 GL 的內容直接繪製在渲染緩衝上,並不流經傳統的畫面擷取路徑。以下介紹如何針對 OpenGL ES 做截圖。
先設定 CAEAGLLayer 的可繪製屬性,保留後緩衝並採 RGBA8 色彩格式:
CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer;
eaglLayer.drawableProperties = @{
kEAGLDrawablePropertyRetainedBacking: [NSNumber numberWithBool:YES],
kEAGLDrawablePropertyColorFormat: kEAGLColorFormatRGBA8
};核心思路是:先用 glReadPixels 從 framebuffer 讀出像素,再包成 CGImage,最後畫進 UIImage:
- (UIImage*)snapshot:(UIView*)eaglview {
GLint backingWidth, backingHeight;
// 綁定用來渲染的 color renderbuffer
glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
// 取得後緩衝尺寸
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);
NSInteger x = 0, y = 0, width = backingWidth, height = backingHeight;
NSInteger dataLength = width * height * 4;
GLubyte *data = (GLubyte*)malloc(dataLength * sizeof(GLubyte));
// 從 framebuffer 讀取像素
glPixelStorei(GL_PACK_ALIGNMENT, 4);
glReadPixels(x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, data);
// 用像素資料建立 CGImage
CGDataProviderRef ref = CGDataProviderCreateWithData(NULL, data, dataLength, NULL);
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGImageRef iref = CGImageCreate(width, height, 8, 32, width * 4, colorspace,
kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast,
ref, NULL, true, kCGRenderingIntentDefault);
// OpenGL ES 以「像素」為單位,這裡要建立以「點」為目標尺寸的繪圖環境
NSInteger widthInPoints, heightInPoints;
if (NULL != UIGraphicsBeginImageContextWithOptions) {
// iOS 4 以後,用 UIGraphicsBeginImageContextWithOptions 並把 scale 設為 view 的 contentScaleFactor
CGFloat scale = eaglview.contentScaleFactor;
widthInPoints = width / scale;
heightInPoints = height / scale;
UIGraphicsBeginImageContextWithOptions(CGSizeMake(widthInPoints, heightInPoints), NO, scale);
} else {
widthInPoints = width;
heightInPoints = height;
UIGraphicsBeginImageContext(CGSizeMake(widthInPoints, heightInPoints));
}
CGContextRef cgcontext = UIGraphicsGetCurrentContext();
// UIKit 座標系與 GL/Quartz 上下相反,畫進翻轉後的 bitmap 以修正方向
CGContextSetBlendMode(cgcontext, kCGBlendModeCopy);
CGContextDrawImage(cgcontext, CGRectMake(0.0, 0.0, widthInPoints, heightInPoints), iref);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// 清理
free(data);
CFRelease(ref);
CFRelease(colorspace);
CGImageRelease(iref);
return image;
}直接呼叫上述方法並傳入 GL 視圖即可取得截圖:
- (UIImage*)snapshot:(UIView*)eaglview