Skip to content

Instantly share code, notes, and snippets.

@junpluse
Last active August 28, 2020 06:14
Show Gist options
  • Save junpluse/db10714937e760d82b56 to your computer and use it in GitHub Desktop.
Save junpluse/db10714937e760d82b56 to your computer and use it in GitHub Desktop.
Take snapshot from CAEAGLLayer
import QuartzCore
import OpenGLES
extension CAEAGLLayer {
func takeSnapshot(from renderBuffer: GLuint? = nil) -> UIImage {
var bufferWidth: GLint = 0
var bufferHeight: GLint = 0
if let buffer = renderBuffer {
glBindRenderbufferOES(GLenum(GL_RENDERBUFFER_OES), buffer)
}
glGetRenderbufferParameterivOES(GLenum(GL_RENDERBUFFER_OES), GLenum(GL_RENDERBUFFER_WIDTH_OES), &bufferWidth)
glGetRenderbufferParameterivOES(GLenum(GL_RENDERBUFFER_OES), GLenum(GL_RENDERBUFFER_HEIGHT_OES), &bufferHeight)
let width = Int(bufferWidth)
let height = Int(bufferHeight)
let length = Int(width * height * 4)
let data = malloc(length * sizeof(GLubyte))
glPixelStorei(GLenum(GL_PACK_ALIGNMENT), 4)
glReadPixels(0, 0, bufferWidth, bufferHeight, GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), data)
let dataProvider = CGDataProviderCreateWithData(nil, data, length, nil)
let colorspace = CGColorSpaceCreateDeviceRGB()
let image = CGImageCreate(width, height, 8, 32, width * 4, colorspace, .ByteOrderDefault, dataProvider, nil, true, .RenderingIntentDefault)!
UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), false, contentsScale)
let context = UIGraphicsGetCurrentContext()
CGContextSetBlendMode(context, .Copy)
CGContextDrawImage(context, CGRect(x: 0, y: 0, width: width, height: height), image)
let renderedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
free(data)
return renderedImage
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment