2014年4月24日木曜日

OpenGLの描画内容を画像にする

-(UIImage *)createImage{
    int backingWidth = self.view.bounds.size.width;   // OpenGLのバッファの幅
    int backingHeight = self.view.bounds.size.height;   // OpenGLのバッファの高さ
    
    NSInteger myDataLength = backingWidth * backingHeight * 4;
    GLubyte *buffer = (GLubyte *) malloc(myDataLength);
    glReadPixels(0, 0, backingWidth, backingHeight, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
    
    // FIXME:上下をひっくり返す。この処理が勿体ない。
    GLubyte *buffer2 = (GLubyte *) malloc(myDataLength);
    for(int y = 0; y <backingHeight; y++)
    {
        memcpy(&buffer2[((backingHeight-1) - y) * backingWidth * 4], &buffer[y * 4 * backingWidth], sizeof(GLubyte) * backingWidth * 4);
    }
    free(buffer);
    
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer, myDataLength, NULL);
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGImageRef imageRef = CGImageCreate(backingWidth, backingHeight, 8, 32, 4 * backingWidth, colorSpaceRef, kCGBitmapByteOrderDefault, provider, NULL, NO, kCGRenderingIntentDefault);
    UIImage *image = [UIImage imageWithCGImage:imageRef];
    return image;


}

0 件のコメント:

コメントを投稿