2014-07-06 16 views
9

Come posso convertire un NSImage in CGImage in Swift? In Objective-C che ho fatto in questo modo:Swift NSImage to CGImage

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

Ora ho provato con:

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; 
    } 
    } 
} 

non riesco a compilare, sto ottenendo l'errore: Could not find an overload for 'init' that accepts the supplied arguments' alla linea let maskRef ...

risposta

7

Ah, ho trovato la soluzione. È perché in Swift hai solo un oggetto non gestito (non ho proprio capito, cosa significa). Ma questo codice funziona ora:

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

destro. È tratto dal libro di Apple: 'Quando Swift importa le API che non sono state annotate, il compilatore non può automaticamente gestire la memoria degli oggetti Core Foundation restituiti. Swift avvolge questi oggetti Core Foundation restituiti in una struttura non gestita . Tutti gli oggetti Core Foundation restituiti indirettamente sono anch'essi non gestiti. Estratto da: Apple Inc. "Uso di Swift con Cocoa e Objective-C". IBooks. https://itunes.apple.com/ru/book/using-swift-cocoa-objective/id888894773?l=it&mt=11 – ovejka

+4

cosa è takeUnretainedValue? non c'è nulla di così rapido. – SpaceDog

18

Ecco quello che sto usando per convertire NSImage a 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) 
} 
+4

Puoi passare 'nil' per' proposalRect' e ottenere lo stesso risultato. –

0

Swift codice 3 e 4 versione: -

if let image = NSImage(named: "Icon"){ 
    let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil) 
}