如何在IOS 6.0上使用SPRectangle保存UIImage时修复错误

时间:2012-11-27 04:16:33

标签: objective-c sparrow-framework

此功能返回黑色图像。我使用麻雀库。

这是我的代码:

-(UIImage *) saveRectangle:(SPRectangle*)rectangle
{
    int numberOfComponents = 8;
    int width = rectangle.width;
    int height = rectangle.height;

    NSInteger bufferLenght = width * height * numberOfComponents;


    NSMutableData * buffer= [NSMutableData dataWithLength:bufferLenght];

    glPixelStorei(GL_PACK_ALIGNMENT, 4); // force 4 byte alignment

    glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, [buffer mutableBytes]);


    CGDataProviderRef ref = CGDataProviderCreateWithData(NULL, [buffer mutableBytes], bufferLenght, NULL);
    CGImageRef iref = CGImageCreate(width, height, 8, 32, width * 4, CGColorSpaceCreateDeviceRGB(), kCGBitmapByteOrderDefault, ref, NULL, true, kCGRenderingIntentDefault);
    uint32_t* pixels = (uint32_t *)malloc(bufferLenght);
    CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width*4, CGImageGetColorSpace(iref), kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Big);
    CGContextTranslateCTM(context, 0.0, height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextDrawImage(context, CGRectMake(0.0, 0.0, width, height), iref);
    CGImageRef outputRef = CGBitmapContextCreateImage(context);
    free(pixels);

    return [UIImage imageWithCGImage:outputRef];
}

1 个答案:

答案 0 :(得分:1)

你展示的代码中只有很少的Sparrow代码(除了与CGRect类似的SPRectangle)。听起来你正试图保存一个麻雀场景的矩形区域的捕获。 Sparrow打算从OpenGL实现细节中抽象出你。你确定使用SPRenderTexture会不容易吗? http://doc.sparrow-framework.org/core/Classes/SPRenderTexture.html

还要确保要返回UIImage而不是SPImage。希望它有所帮助。