将渐变背景添加到SKScene

时间:2018-09-02 16:06:46

标签: swift3 gradient skscene

我一直在研究如何在我的SKScene中添加渐变背景。使用几种来源(例如SKTexture from UIImage looks differentUIImage from CALayer - iPhone SDK),我执行了以下操作:

class GameScene: SKScene
{
    override func didMove(to view: SKView)
    {
        let backgroundImg = UIImage.imageFromLayer(layer: IGABackgroundLayer().gradientMetar())

        if let backgroundImg = backgroundImg
        {
            let backgroundTexture = SKTexture(image: backgroundImg)
            let background = SKSpriteNode(texture: backgroundTexture)
            background.position = CGPoint(x: frame.width/2, y: frame.height/2)
            addChild(background)
        }
    }
}

extension UIImage
{
    static func imageFromLayer(layer: CALayer) -> UIImage?
    {
        UIGraphicsBeginImageContextWithOptions(layer.bounds.size,
                                               layer.isOpaque, UIScreen.main.scale)

        defer { UIGraphicsEndImageContext() }

        // Don't proceed unless we have context
        guard let context = UIGraphicsGetCurrentContext() else
        {
            return nil
        }

        layer.render(in: context)
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}


class IGABackgroundLayer
{
    func gradientMetar() -> CAGradientLayer
    {
        let colorOne = UIColor(red:(0/255.0),green:(0/255.0),blue:(50/255.0),alpha:1.0)
        let colorTwo = UIColor(red:(0/255.0),green:(0/255.0),blue:(200/255.0),alpha:1.0)
        let colorThree = UIColor(red:(0/255.0),green:(255/255.0),blue:(255/255.0),alpha:1.0)

        let colors = [colorOne.cgColor,colorTwo.cgColor,colorThree.cgColor]

        let stopOne : NSNumber = NSNumber(value: 0.50)
        let stopTwo : NSNumber = NSNumber(value: 0.80)
        let stopThree : NSNumber = NSNumber(value: 1.0)

        let locations = [stopOne, stopTwo, stopThree]

        let headerLayer : CAGradientLayer = CAGradientLayer()

        headerLayer.colors = colors
        headerLayer.locations = locations

        return headerLayer

    }
}

它仍然不起作用-没有渐变背景。

有人可以指出我正确的方向吗?

非常感谢!

0 个答案:

没有答案