0

Ich habe ein Array von NSColor s, und ein Array von CGFloat s bedeutet Gradientenstopps. Ich kann nicht herausfinden, wie man diese Arrays verwendet, um eine NSGradient zu initialisieren.Wie kann ich einen NSGradient aus einem Array von Farben und Floats erstellen?

Ich habe versucht, diese in ein Array von (NSColor, CGFloat) s zu machen, aber NSGradient(colorsAndLocations: wird es nicht nehmen, da es varargs erwartet:

The code <code>let gradient = NSGradient(colorsAndLocations: colorsAndLocations)</code> yielding the error <code>Cannot convert value of type '[(NSColor, CGFloat)]' to expected argument type '(NSColor, CGFloat)'</code>

Und NSGradient(colors:, atLocations:, colorSpace:) erwartet eine UnsafePointer, die ich keine Ahnung, wie man richtig Handle in Swift, wenn es überhaupt so ist.

Antwort

1

Ich nehme an, Sie kennen diese Nutzung:

let cAndL: [(NSColor, CGFloat)] = [(NSColor.redColor(), 0.0), (NSColor.greenColor(), 1.0)] 
let gradient = NSGradient(colorsAndLocations: cAndL[0], cAndL[1]) 

Leider Swift uns nicht bieten eine Möglichkeit, Arrays zu variadische Funktionen zu geben.


Und der zweite Teil. Wenn eine API das Attribut UnsafePointer<T> als Array beansprucht, können Sie ein Swift-Array von T erstellen und direkt an die API übergeben.

let colors = [NSColor.redColor(), NSColor.greenColor()] 
let locations: [CGFloat] = [0.0, 1.0] 
let gradient2 = NSGradient(colors: colors, atLocations: locations, colorSpace: NSColorSpace.genericRGBColorSpace()) 

Wenn Sie eine Array von (NSColor, CGFloat) nutzen möchten, können Sie so etwas schreiben:

let gradient3 = NSGradient(colors: cAndL.map{$0.0}, atLocations: cAndL.map{$0.1}, colorSpace: NSColorSpace.genericRGBColorSpace()) 
+0

_ "Sie Swift Array von T erzeugen können, und liefern sie direkt an die API "_ Ist dies garantiert sicher? –

+1

@BenLeggiero, sicherlich. Weitere Informationen finden Sie im Abschnitt "Constant Pointers" in diesem Dokument (https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithCAPIs.html#//apple_ref/doc/uid/TP40014216-CH8-ID23). – OOPer