ios - 如果需要返回它,如何释放 CGImageRef?

标签 ios macos cocoa core-graphics

我有一种方法可以调整 CGImageRef 的大小并返回 CGImageRef。问题是最后几行,我需要以某种方式释放但之后返回它。有任何想法吗?谢谢

 -(CGImageRef)resizeImage:(CGImageRef *)anImage width:(CGFloat)width height:(CGFloat)height
{

    CGImageRef imageRef = *anImage;

    CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef);

    if (alphaInfo == kCGImageAlphaNone)
        alphaInfo = kCGImageAlphaNoneSkipLast;


    CGContextRef bitmap = CGBitmapContextCreate(NULL, width, height, CGImageGetBitsPerComponent(imageRef), 4 * width, CGImageGetColorSpace(imageRef), alphaInfo);

    CGContextDrawImage(bitmap, CGRectMake(0, 0, width, height), imageRef);

    CGImageRef ref = CGBitmapContextCreateImage(bitmap);

    CGContextRelease(bitmap);
    CGImageRelease(ref); //issue here

    return ref;

}

最佳答案

Cocoa 内存管理命名策略规定,您拥有一个对象,该对象是从名称以 alloccopynew.
Clang 静态分析器也遵守此规则。

请注意,Core Foundation 的约定略有不同。详情可见Apple's Advanced Memory Management Programming Guide .

我修改了您的上述方法以符合该命名约定。我在传入 anImage 时也删除了星号,因为 CGImageRef 已经是一个指针。 (或者这是故意的?)
请注意,您拥有返回的 CGImage 并且稍后必须 CGImageRelease 它。

-(CGImageRef)newResizedImageWithImage:(CGImageRef)anImage width:(CGFloat)width height:(CGFloat)height
{
    CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(anImage);
    if (alphaInfo == kCGImageAlphaNone)
    {
        alphaInfo = kCGImageAlphaNoneSkipLast;
    }
    CGContextRef bitmap = CGBitmapContextCreate(NULL, width, height, CGImageGetBitsPerComponent(anImage), 4 * width, CGImageGetColorSpace(anImage), alphaInfo);
    CGContextDrawImage(bitmap, CGRectMake(0, 0, width, height), anImage);
    CGImageRef image = CGBitmapContextCreateImage(bitmap);
    CGContextRelease(bitmap);
    return image;
}

关于ios - 如果需要返回它,如何释放 CGImageRef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17016247/

相关文章:

我们可以像在 Windows 上一样直接用 C 在 OS X 和 Linux 上制作图形吗?

c# - 如何从 OSX 中的终端运行 Windows.Forms C# 程序?

iphone - TTThumbsviewcontroller 停止加载缩略图

cocoa - 以一种让我可以随意重新排序的方式向 NSTableview 添加值

cocoa - CF内存分配示例

ios - Objective C 类找不到 Swift 协议(protocol)的定义

javascript - 在 iOS 版 Chrome 上拦截 AJAX 请求?

ios - 使用授权从 Amazon S3 执行 HTTP GET 的最少 iOS 代码?

cocoa - 如何在 Mac OSX 上使用 Cocoa 创建类似 OSD 的窗口?

ios - 如何删除 Swift iOS8 中的最后一张照片?