CGImage绘制调用的不必要的内存消耗

时间:2019-04-17 10:06:28

标签: macos memory core-graphics

我正在研究一个使用Core Graphics将图像解码为RGBA软件缓冲区的项目。

func LoadImage(imageFile: CFString, imageData: inout Array<UInt32>) {
        let imgUrl: CFURL = CFURLCreateWithFileSystemPath(nil, imageFile, CFURLPathStyle.cfurlposixPathStyle, false);
        let imgSource: CGImageSource = CGImageSourceCreateWithURL(imgUrl, nil)!;
        let imgProperties: NSDictionary = CGImageSourceCopyPropertiesAtIndex(imgSource, 0, nil)!;
        let pixelWidth: Int = (imgProperties.object(forKey: kCGImagePropertyPixelWidth) as! NSNumber).intValue;
        let pixelHeight: Int = (imgProperties.object(forKey: kCGImagePropertyPixelHeight) as! NSNumber).intValue;
        let img: CGImage = CGImageSourceCreateImageAtIndex(imgSource, 0, nil)!;
        let colorspace = CGColorSpaceCreateDeviceRGB();

        imageData = Array<UInt32>(repeating: 0x00000000, count: pixelWidth * pixelHeight);

        let ctx: CGContext = CGContext(data: &imageData[0], width: pixelWidth, height: pixelHeight, bitsPerComponent: 8, bytesPerRow: pixelWidth * 4, space: colorspace, bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue)!;

        ctx.draw(img, in: CGRect(x: 0, y: 0, width: pixelWidth, height: pixelHeight));
    }

调用此函数时,几次(即使使用相同的图像文件路径)内存消耗也会迅速增加。使用7600x5066 JPEG,我很快获得了2GB以上的存储空间,仅以毫秒为单位对其进行了多次调用。活动监视器会在绘图调用返回后立即显示实际内存和可清除内存的增加。真正的内存和可清除的内存都不断增加到大约2 GB,但似乎没有增加。

假定可清除的内存是真实内存(即进程的虚拟内存)的一部分。我希望系统能够执行“可清除”操作,即在给定时间清除它。 这样做似乎是因为该数量从未超过2 GB,有时甚至下降到1.5 GB。

由于我目前仅限于32位环境,因此这很关键。 有没有办法防止多余的分配最终被清除? 如果没有,有没有办法强制清除它?

0 个答案:

没有答案