UIGraphicsBeginImageContext导致内存(泄漏)溢出

时间:2012-01-09 09:55:38

标签: iphone objective-c cocoa-touch cocos2d-iphone uiimage

在我的代码中,我将图像的大小拉伸到指定的大小。到目前为止代码工作正常。 我遇到的问题是“UIGraphicsBeginImageContext()”没有释放新图像的内存。因此,大约10分钟后内存已满,应用程序被IOS终止。

有没有人能解决这个问题?

- (CCSprite *)createStretchedSignFromString:(NSString *)string withMaxSize:(CGSize)maxSize withImage:(UIImage *)signImage
{
    // Create a new image that will be stretched with 10 px cap on each side
    UIImage *stretchableSignImage = [signImage stretchableImageWithLeftCapWidth:10 topCapHeight:10];

    // Set size for new image
    CGSize newImageSize = CGSizeMake(260.f, 78.0f);

    // Create new graphics context with size of the answer string and some cap
    UIGraphicsBeginImageContext(newImageSize);

    // Stretch image to the size of the answer string
    [stretchableSignImage drawInRect:CGRectMake(0.0f, 0.0f, newImageSize.width, newImageSize.height)];

    // Create new image from the context
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();

    // End graphics context
    UIGraphicsEndImageContext();

    // Create new texture from the stretched
    CCTexture2D *tex = [[CCTexture2D alloc] initWithImage:resizedImage];

    CCSprite *spriteWithTex = [CCSprite spriteWithTexture:tex];

    [[CCTextureCache sharedTextureCache] removeTexture:tex];

    [tex release];

    // Return new sprite for the sign with the texture  
    return spriteWithTex;
}

由此代码调用:

// Create image from image path
UIImage *targetSignImage = [UIImage imageWithContentsOfFile:targetSignFileName];

// Create new sprite for the sign with the texture
CCSprite *plainSign = [self createStretchedSignFromString:answerString withMaxSize:CGSizeMake(260.0f, 78.0f) withImage:targetSignImage];

到目前为止,谢谢你。

1 个答案:

答案 0 :(得分:2)

我找到了解决问题的方法。

首先,上面显示的代码是正确的,没有泄漏。

问题是由删除了planSign作为孩子的精灵造成的。精灵被一个在不同线程上运行的计时器删除,所以在其他NSAutoreleasePool上运行。

[timerClass removeTarget:targetWithSign]发布了一个空池。

[timerClass performSelectorOnMainThread:@selector(removeTarget:) withObject:targetWithSign waitUntilDone:NO];发布了正确的池,其中包含目标精灵及其子plainSign

感谢SAKrisT和你的建议。