本文介绍了Swift NSImage到CGImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Swift中将NSImage转换为CGImage?在Objective-C我做了这样:

How can I convert a NSImage to CGImage in Swift? In Objective-C I did it like this:

- (CGImageRef)CGImage {
    NSData *imageData = self.TIFFRepresentation;
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL);
    CGImageRef maskRef =  CGImageSourceCreateImageAtIndex(source, 0, NULL);
    return maskRef;
}

现在我试过:

extension NSImage {
    var CGImage: CGImageRef {
    get {
        let imageData = self.TIFFRepresentation
        let source = CGImageSourceCreateWithData(imageData as CFDataRef, nil)
        let maskRef = CGImageSourceCreateImageAtIndex(source, UInt(0), nil)
        return maskRef;
    }
    }
}

我收到错误:无法找到一个重载的'init'接受提供的参数'在行 let maskRef ...

推荐答案

这里是我用来将NSImage转换为CGImage:

Here's what I'm using to convert NSImage to CGImage:

let image = NSImage(named:"image")
if let image = image {
    var imageRect:CGRect = CGRectMake(0, 0, image.size.width, image.size.height)
    var imageRef = image.CGImageForProposedRect(&imageRect, context: nil, hints: nil)
}

这篇关于Swift NSImage到CGImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 03:52