• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - iOS 中的内存泄漏与 CGContextRef

[复制链接]
菜鸟教程小白 发表于 2022-12-12 23:41:02 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我有一组代码获取存储在 UIImageView 中的图像并修改其内容以复制到不同 UIImageView 的新图像中。问题是当我分析项目时,这段代码总是从我的编译器收到内存警告。我尝试以多种方式实现此代码,但我总是收到不同类型的内存警告。编译器的输出显示“调用函数 'CGBitMapContextCreateImage' 返回一个具有 +1 保留计数的核心基础对象”,这导致图像对象的保留计数为 +1。如果我自动释放图像对象,编译器会发出内存警告,自动释放被调用多次,并且图像对象最初的保留计数为 0。

这两个编译器警告不是矛盾的吗?如何修复此代码以确保不会发生内存泄漏?

-(UIImage *) makeImageLight{

UIImage * image = self.masterImage.image;

NSUInteger width = image.size.width;
NSUInteger height = image.size.height;
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = width * bytesPerPixel;

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);

CGColorSpaceRelease(colorSpace);

CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = height}, image.CGImage);

UInt8* data = (UInt8*)CGBitmapContextGetData(bmContext);


for (size_t i = 0; i < CGBitmapContextGetWidth(bmContext); i++)
{
    for (size_t j = 0; j < CGBitmapContextGetHeight(bmContext); j++)
    {
        int pixel = j * CGBitmapContextGetWidth(bmContext) + i;

        pixel = pixel * 4;

        UInt8 red = data[pixel + 1];         // If you need this info, enable it
        UInt8 green = data[pixel + 2]; // If you need this info, enable it
        UInt8 blue = data[pixel + 3];    // If you need this info, enable it

        red = ((255 - red) * .3) + red;
        green = ((255 - green) * .3) + green;

        data[pixel + 1] = red;
        data[pixel + 2] = green;
        data[pixel + 3] = blue;

    }
}

// memory warning occurs in the following line:

image = [UIImage imageWithCGImage:CGBitmapContextCreateImage(bmContext)];

CGContextRelease(bmContext);

return image;

}

没关系,我通过添加以下代码来修复它以释放从上下文创建的 CGImage:

CGImageRef imageRef = CGBitmapContextCreateImage(bmContext);

image = [UIImage imageWithCGImage:imageRef];

CGImageRelease(imageRef);



Best Answer-推荐答案


您使用 CGBitmapContextCreateImage() 创建了一个 CGImage,但您还没有发布该 CGImage

您需要将UIImage创建行拆分如下:

CGImageRef cgimage = CGBitmapContextCreateImage(bmContext);
image = [UIImage imageWithCGImage:cgimage];
CGImageRelease(cgimage);

关于ios - iOS 中的内存泄漏与 CGContextRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13226268/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap