1

我有一个带有透明边框的图像,我正在尝试按照此处找到的 Apple 指南直接操作图像像素。在设备上运行时一切正常。但是,当我在模拟器上运行我的代码时,我发现每次调用此函数时,图像的透明边框都会慢慢变黑。奇怪的是,即使我不修改图像数据,每次调用这个函数时,透明边框仍然开始变黑。例如,即使我的图像处理代码调用CGBitmapContextGetData但不使用返回的数据指针,我也会看到同样的问题。为了使模拟器上的问题消失,我必须注释掉调用CGBitmapContextGetData(当然还有数据指针的释放)。仍然在模拟器上修改图像的示例代码:

+ (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;    
}

在这里阅读了有关如何在设备和模拟器之间以不同方式管理图像的评论和答案,但它并没有帮助我找出我的问题。

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

我目前正在主线程中进行所有图像操作以调试此问题。

规格:Mountain Lion,XCode 4.5.2,iOS 6 设备,iOS 6 模拟器

4

1 回答 1

0

我能够通过允许 Quartz 分配和管理位图(Apple doc)的内存来解决这个问题。为此,我更新了对 in 的调用以CGBitmapContextCreate传递CreateARGBBitmapContextNULL,并删除了对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. 现在它似乎在设备和模拟器上都可以正常工作,没有任何问题。

于 2012-11-09T17:11:07.540 回答