代码之家  ›  专栏  ›  技术社区  ›  Thoms

调整UIImage大小时内存泄漏

  •  0
  • Thoms  · 技术社区  · 8 年前

    我已经阅读了关于这个主题的多个帖子,但我的问题仍然存在。 当我使用以下代码调整图像大小时:

    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),我最终会收到内存警告,应用程序最终崩溃。 有什么建议吗?

    2 回复  |  直到 8 年前
        1
  •  1
  •   user7014451 user7014451    8 年前

    这是我的分机,基本上和你的一样。因为我没有内存问题,看起来这可能就是问题所在。

    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!
        }
    }
    
        2
  •  0
  •   Baig    8 年前

    问题是:

    UIGraphicsGetImageFromCurrentImageContext() thumb = nil 使用后。

    var thumb = UIImage()
    
    autoreleasepool {
       thumb = lionImage.thumbnailWithMaxSize(image: lionImage, maxSize: 2000)
       let myImage:UIImage = UIImage(UIImagePNGRepresentation(thumb));
       thumb = nil
    }
    myImageView.image = myImage