How to draw a gradient using SKKeyframeSequence: according to Apple docs

Apple docs on SKKeyframeSequence contain a short sample code for creating a gradient:

let colorSequence = SKKeyframeSequence(keyframeValues: [SKColor.green, SKColor.yellow, SKColor.red, SKColor.blue], times: [0, 0.25, 0.5, 1]) colorSequence.interpolationMode = .linear stride(from: 0, to: 1, by: 0.001).forEach { let color = colorSequence.sample(atTime: CGFloat($0)) as! SKColor } 

In combination with some kind of drawing system, this means that it outputs the following: enter image description here How can this be done from sampling the color sequence in the demo code?

ps I have no clue how to draw this with SpriteKit objects, hence the lack of code attempt. I'm not asking for code, just the answer to the question of how to use this β€œarray” of colors to create a gradient that can be used as a texture in SpriteKit.

+5
source share
1 answer

For some reason, colors are different, but here's what I came up with using their source code:

PG setup:

 import SpriteKit import PlaygroundSupport let sceneView = SKView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 1000, height: 450))) let scene = SKScene(size: CGSize(width: 1000, height: 450)) LOADSCENE: do { scene.backgroundColor = .white scene.anchorPoint = CGPoint(x: 0, y: 0.5) scene.physicsWorld.gravity = CGVector.zero sceneView.presentScene(scene) PlaygroundPage.current.liveView = sceneView } 

Decision:

 // Utility func: func drawLine(from point1: CGPoint, to point2: CGPoint, color: SKColor) { let linePath = CGMutablePath() linePath.move(to: point1) linePath.addLine(to: point2) let newLine = SKShapeNode(path: linePath) newLine.strokeColor = color newLine.lineWidth = 1 newLine.zPosition = 10 scene.addChild(newLine) newLine.position.x = point1.x } // Holds our soon-to-be-generated colors: var colors = [SKColor]() LOADCOLORS: do { let colorSequence = SKKeyframeSequence(keyframeValues: [SKColor.green, SKColor.yellow, SKColor.red, SKColor.blue], times: [0, 0.25, 0.5, 1]) colorSequence.interpolationMode = .linear stride(from: 0, to: 1, by: 0.001).forEach { colors.append(colorSequence.sample(atTime: CGFloat($0)) as! SKColor) } } DRAWGRAD: do { for i in 1...999 { let p1 = CGPoint(x: CGFloat(i), y: scene.frame.minY) let p2 = CGPoint(x: CGFloat(i), y: scene.frame.maxY) drawLine(from: p1, to: p2, color: colors[i]) } print("Give me my 25 cookie points, please and TY") } 

enter image description here

Then you can get this as a texture as such:

 let texture = sceneView.texture(from: scene) 

Rendering took about a million years to render on my gen2 i5 at 2.6ghz for some reason. Must think about it, unless it's just a PG bug ...

+5
source

Source: https://habr.com/ru/post/1263271/


All Articles