0

I'm trying to use a color gradient for the background of a scene in my sprite kit game. So it looks similar to this:

enter image description here

I need help solving the following error:

Type 'UIImage' has no member 'radialGradientImage'

The code:

import UIKit
import SpriteKit
import StoreKit
import GameKit
import AVFoundation
import SpriteKit.SKTexture

class Start: SKScene {
    let color1 = UIColor(red: 255/255, green: 153/255, blue: 102/255, alpha: 1)
    let color2 = UIColor(red: 255/255, green: 204/255, blue: 153/255, alpha: 1)

    //Error ->
    let backgroundImg = UIImage.radialGradientImage(size: frame.size, outerColor: color1, innerColor: color2)

    //

    let backgroundTexture = SKTexture(image: backgroundImg)
    let background = SKSpriteNode(texture: backgroundTexture)

    override func didMove(to view: SKView) {
        //Background
        background.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
        addChild(background)
    }

    static func radialGradientImage(size: CGSize, outerColor: UIColor, innerColor: UIColor) -> UIImage
    {
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let gradient = CGGradient(colorsSpace: colorSpace, colors: [outerColor.cgColor, innerColor.cgColor] as CFArray, locations: [1.0, 0.0])
        let center = CGPoint(x: size.width / 2.0, y: size.height / 2.0)

        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
        let imageContext = UIGraphicsGetCurrentContext()

        imageContext!.drawRadialGradient(gradient!, startCenter: center, startRadius: 0.0, endCenter: center, endRadius: size.width / 2.0, options: CGGradientDrawingOptions.drawsAfterEndLocation)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image!
    }
}
Taazar
  • 1,545
  • 18
  • 27
Joy Lucas
  • 61
  • 1
  • 10

1 Answers1

0

radialGradientImage is a static method of your Start class, not the UIImage class.

You want:

let backgroundImg = Start.radialGradientImage(size: frame.size, outerColor: color1, innerColor: color2)

But that is going to fail with more errors because you can't access frame, color1, or color2 there.

You need to change let to lazy var:

lazy var backgroundImg = Start.radialGradientImage(size: frame.size, outerColor: color1, innerColor: color2)
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Thanks that worked well. Is there also a possibility to use a vertical gradient instead of a radial gradient (like the gradient from the screenshot in my question)? – Joy Lucas Nov 25 '18 at 15:44
  • That's a completely separate question. Mark this one as solved by clicking the checkmark to the left of the answer. If you have a new question about gradients, post an new question if needed after doing some research first. – rmaddy Nov 25 '18 at 15:46