Victor --------
Victor --------

Reputation: 512

How to blur a scene in Swift 2

I'm trying to blur a scene when I pause a game and I'm following an example but I'm unable to work it out in Swift 2.0.

A lot of tutorials say to just take a screenshot and then present that screenshot as blurred but I don't think that's a good idea, I'd like to blur the view without a screenshot.

here is my attempt:

func createlayers() {
    let node = SKEffectNode()
    node.shouldEnableEffects = false
    let filter: CIFilter = CIFilter(name: "CIGaussianBlur", withInputParameters: ["inputRadius" : NSNumber(double:1.0)])!
    node.filter = filter
}

func blurWithCompletion() {
    let duration: CGFloat = 0.5
    scene!.shouldRasterize = true
    scene!.shouldEnableEffects = true
    scene!.runAction(SKAction.customActionWithDuration(0.5, actionBlock: { (node: SKNode, elapsedTime: CGFloat) in
        let radius = (elapsedTime/duration)*10.0
        (node as? SKEffectNode)!.filter!.setValue(radius, forKey: "inputRadius")

    }))
}

func pauseGame()
{
    self.blurWithCompletion()
    self.view!.paused = true 

}

I get "fatal error: unexpectedly found nil while unwrapping an Optional value"

Upvotes: 2

Views: 541

Answers (1)

Aruna Mudnoor
Aruna Mudnoor

Reputation: 4825

create layers method is not required. Use this updated blurWithCompletion method:

    func blurWithCompletion() {
    let duration: CGFloat = 0.5
    let filter: CIFilter = CIFilter(name: "CIGaussianBlur", withInputParameters: ["inputRadius" : NSNumber(double:1.0)])!
    scene!.filter = filter
    scene!.shouldRasterize = true
    scene!.shouldEnableEffects = true
    scene!.runAction(SKAction.customActionWithDuration(0.5, actionBlock: { (node: SKNode, elapsedTime: CGFloat) in
        let radius = (elapsedTime/duration)*10.0
        (node as? SKEffectNode)!.filter!.setValue(radius, forKey: "inputRadius")

    }))
}

Upvotes: 2

Related Questions