2012-11-08 70 views
1

我有一个透明边框的图像,我试图直接操纵图像像素,遵循苹果指南发现here。在设备上运行时一切正常。但是,当我在模拟器上运行我的代码时,发现每次调用此函数时,图像的透明边框都会慢慢变黑。奇怪的是,即使我不修改图像数据,每次调用此函数时,透明边框仍会变黑。例如,即使我的图像处理代码调用CGBitmapContextGetData但不使用返回的数据指针,我也会看到同样的问题。为了让问题在模拟器上消失,我必须将CGBitmapContextGetData的调用注释掉(并且当然可以释放数据指针)。示例代码还修改仿真器上的图像:iPhone差异处理设备和模拟器之间的图像

+ (UIImage *) updateImage:(UIImage *)inputImage 
{ 
    UIImage *updatedImage; 

    /* Update colors in image appropriately */ 
    CGImageRef image = [inputImage CGImage]; 

    CGContextRef cgctx = [ColorHandler CreateARGBBitmapContext:image]; 
    if (cgctx == NULL) 
    { 
     // error creating context 
     NSLog(@"Error creating context.\n"); 
     return nil; 
    } 

    size_t w = CGImageGetWidth(image); 
    size_t h = CGImageGetHeight(image); 
    CGRect rect = {{0,0},{w,h}}; 

    // Draw the image to the bitmap context. Once we draw, the memory 
    // allocated for the context for rendering will then contain the 
    // raw image data in the specified color space. 
    CGContextDrawImage(cgctx, rect, image); 

    // Now we can get a pointer to the image data associated with the bitmap 
    // context. 
    void *data = CGBitmapContextGetData(cgctx); 

    CGImageRef ref = CGBitmapContextCreateImage(cgctx); 
    updatedImage = [UIImage imageWithCGImage:ref]; 
    // When finished, release the context 
    CGContextRelease(cgctx); 
    CGImageRelease(ref); 

    // Free image data memory for the context 
    if (data) 
    { 
     free(data); 
    } 

    return updatedImage;  
} 

我读了关于如何图像的设备和模拟器之间不同的方式管理the comments and answers here,但它并没有帮助我找出我的问题。

我的CreateARGBBitmapContext和示例之间唯一的区别是我呼吁CGColorSpaceCreateDeviceRGB而不是CGColorSpaceCreateWithName因为我的目标是iOS。该图像在iOS设备上运行时完全按照设计进行编辑。

我目前正在主线程中调试此问题的所有图像处理。

规格:山狮子时,Xcode 4.5.2,iOS 6的设备的iOS 6模拟器

回答

0

我能够通过允许石英为位图(Apple doc)分配和管理的内存来解决问题。为此,我更新了CGBitmapContextCreate 中的呼叫以传递NULL,并且删除了所有对bitmapData的引用。

// Create the bitmap context. We want pre-multiplied ARGB, 8-bits 
// per component. Regardless of what the source image format is 
// (CMYK, Grayscale, and so on) it will be converted over to the format 
// specified here by CGBitmapContextCreate. 
context = CGBitmapContextCreate (NULL, 
           pixelsWide, 
           pixelsHigh, 
           8,  // bits per component 
           bitmapBytesPerRow, 
           colorSpace, 
           kCGImageAlphaPremultipliedFirst); 

然后,在updateImage方法,我删除的data的释放。现在它似乎可以在设备和模拟器上工作而没有任何问题。

+0

也许你没有调零传递给CGBitmapContextCreate()的内存? –

+0

@tc。我没有将传递给CGBitmapContextCreate的内存置零。苹果的例子也没有把记忆归零。我没有机会去测试这个问题是否能解决问题,但是你认为它会是什么?我假设CGContextDrawImage无论如何都会覆盖所有的数据。 – Bill

+1

如果您的图片具有透明度,那么'CGContextDrawImage'默认会进行alpha混合;你可以用'kCGBlendModeCopy'直接复制(也许这就是你想要的效率)。如果你不需要iOS 4以下的支持,我还建议使用'UIGraphicsBeginImageContextWithOptions()'。 –

相关问题