调整UIImage大小时发生内存泄漏 [英] Memory leak when resizing UIImage

查看:274
本文介绍了调整UIImage大小时发生内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了有关该主题的多个主题,但是我的问题仍然存在. 当我使用以下代码调整图像大小时:

I've read through multiple threads concerning the topic but my problem still persists. When I'm resizing an Image with following code:

extension UIImage {
  func thumbnailWithMaxSize(image:UIImage, maxSize: CGFloat) -> UIImage {
    let width = image.size.width
    let height = image.size.height
    var sizeX: CGFloat = 0
    var sizeY: CGFloat = 0
    if width > height {
        sizeX = maxSize
        sizeY = maxSize * height/width
    }
    else {
        sizeY = maxSize
        sizeX = maxSize * width/height
    }

    UIGraphicsBeginImageContext(CGSize(width: sizeX, height: sizeY))
    let rect = CGRect(x: 0.0, y: 0.0, width: sizeX, height: sizeY)
    UIGraphicsBeginImageContext(rect.size)
    draw(in: rect)
    let thumbnail = UIGraphicsGetImageFromCurrentImageContext()!;

    UIGraphicsEndImageContext()

    return thumbnail

}


override func viewDidLoad() {
    super.viewDidLoad()

    let lionImage = UIImage(named: "lion.jpg")!

    var thumb = UIImage()

    autoreleasepool {
        thumb = lionImage.thumbnailWithMaxSize(image: lionImage, maxSize: 2000)
    }
    myImageView.image = thumb
}

...内存未释放.因此,当我浏览多个ViewController(例如使用PageViewController)时,我最终会收到内存警告,并且应用最终崩溃. 我也尝试通过UIImage(contentsOfFile:path)加载图像,但没有成功. 有什么建议?

...the memory is not released. So when I navigate through multiple ViewControllers (e.g. with a PageViewController) I end up getting memory warnings and the app eventually crashes. I also tried to load the image via UIImage(contentsOfFile: path) without success. Any suggestions?

推荐答案

我注意到您的代码以两个上下文开始,但仅以一个上下文结束.

I noticed your code beginning two contexts but only ending one.

这是我的扩展名,与您的扩展名基本相同.由于我没有内存问题,因此可能是问题所在.

Here's my extension, which is basically the same as your's. Since I'm not having memory issues, it looks like that may be the issue.

extension UIImage {
    public func resizeToRect(_ size : CGSize) -> UIImage {
        UIGraphicsBeginImageContext(size)
        self.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext();
        return resizedImage!
    }
}

这篇关于调整UIImage大小时发生内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆