如何在SpriteKit中模糊场景?

时间:2014-03-18 20:54:33

标签: objective-c sprite-kit

如何在SpriteKit的SKScene中为所有节点添加高斯模糊(没有固定数量的节点)?稍后将在场景顶部添加标签,这将是我的暂停菜单。 几乎任何事情都会有所帮助!

这样的事情就是我想要的: Gaussian pause menu

7 个答案:

答案 0 :(得分:31)

您正在寻找的是SKEffectNode。它将CoreImage过滤器应用于自身(以及所有子节点)。只需将它作为场景的根视图,给它一个CoreImage的模糊滤镜,然后就可以了。

例如,我设置了一个SKScene,其中SKEffectNode是第一个子节点,另一个属性root包含弱引用:

-(void)createLayers{
  SKEffectNode *node = [SKEffectNode node];
  [node setShouldEnableEffects:NO];
  CIFilter *blur = [CIFilter filterWithName:@"CIGaussianBlur" keysAndValues:@"inputRadius", @1.0f, nil];
  [node setFilter:blur];
  [self setRoot:node];
}

这是我用来(动画!)场景模糊的方法:

-(void)blurWithCompletion:(void (^)())handler{
  CGFloat duration = 0.5f;
  [[self root] setShouldRasterize:YES];
  [[self root] setShouldEnableEffects:YES];
  [[self root] runAction:[SKAction customActionWithDuration:duration actionBlock:^(SKNode *node, CGFloat elapsedTime){
    NSNumber *radius = [NSNumber numberWithFloat:(elapsedTime/duration) * 10.0];
    [[(SKEffectNode *)node filter] setValue:radius forKey:@"inputRadius"];
  }] completion:handler];
}

请注意,和你一样,我将它用作暂停画面,所以我光栅化了场景。如果您希望场景在模糊时进行动画处理,则应该setShouldResterize:NO

如果您对动画转换为模糊不感兴趣,可以随时将过滤器设置为初始半径10.0f左右,并在需要时执行简单的setShouldEnableEffects:YES打开它。

另请参阅:SKEffectNode class reference

<强> 更新:
请参阅下面的Markus的评论。他指出SKScene实际上是SKEffectNode的子类,所以你真的应该能够在场景中调用所有这些,而不是在你的节点树中任意插入一个效果节点

答案 1 :(得分:12)

使用来自http://www.bytearray.org/?p=5360

的@Bendegúz的答案和代码来补充这一点

我能够在我目前正在IOS 8 Swift中完成的游戏项目中使用它。返回SKSpriteNode而不是UIImage,做得有点不同。另请注意我的unwrapped currentScene.view! call是一个弱的GameScene引用,但应该根据你调用这些方法的位置使用self.view.frame。我的暂停屏幕在一个单独的HUD类中调用,因此为什么会这样。

我认为这可以更优雅地完成,也许更像是@ jemmons的答案。只是想在使用全部或部分Swift代码编写的SpriteKit项目中帮助其他任何尝试这样做的人。

func getBluredScreenshot() -> SKSpriteNode{

    create the graphics context
    UIGraphicsBeginImageContextWithOptions(CGSize(width: currentScene.view!.frame.size.width, height: currentScene.view!.frame.size.height), true, 1)

    currentScene.view!.drawViewHierarchyInRect(currentScene.view!.frame, afterScreenUpdates: true)

    // retrieve graphics context
    let context = UIGraphicsGetCurrentContext()

    // query image from it
    let image = UIGraphicsGetImageFromCurrentImageContext()

    // create Core Image context
    let ciContext = CIContext(options: nil)
    // create a CIImage, think of a CIImage as image data for processing, nothing is displayed or can be displayed at this point
    let coreImage = CIImage(image: image)
    // pick the filter we want
    let filter = CIFilter(name: "CIGaussianBlur")
    // pass our image as input
    filter.setValue(coreImage, forKey: kCIInputImageKey)

    //edit the amount of blur
    filter.setValue(3, forKey: kCIInputRadiusKey)

    //retrieve the processed image
    let filteredImageData = filter.valueForKey(kCIOutputImageKey) as CIImage
    // return a Quartz image from the Core Image context
    let filteredImageRef = ciContext.createCGImage(filteredImageData, fromRect: filteredImageData.extent())
    // final UIImage
    let filteredImage = UIImage(CGImage: filteredImageRef)

    // create a texture, pass the UIImage
    let texture = SKTexture(image: filteredImage!)
    // wrap it inside a sprite node
    let sprite = SKSpriteNode(texture:texture)

    // make image the position in the center
    sprite.position = CGPointMake(CGRectGetMidX(currentScene.frame), CGRectGetMidY(currentScene.frame))

    var scale:CGFloat = UIScreen.mainScreen().scale

    sprite.size.width  *= scale

    sprite.size.height *= scale

    return sprite


}


func loadPauseBGScreen(){

    let duration = 1.0

    let pauseBG:SKSpriteNode = self.getBluredScreenshot()

    //pauseBG.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
    pauseBG.alpha = 0
    pauseBG.zPosition = self.zPosition + 1
    pauseBG.runAction(SKAction.fadeAlphaTo(1, duration: duration))

    self.addChild(pauseBG)

}

答案 2 :(得分:10)

这是我暂停屏幕的解决方案。 它将截取屏幕截图,模糊它,之后用动画显示它。 如果你不想浪费太多fps,我认为你应该这样做。

-(void)pause {
    SKSpriteNode *pauseBG = [SKSpriteNode spriteNodeWithTexture:[SKTexture textureWithImage:[self getBluredScreenshot]]];
    pauseBG.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
    pauseBG.alpha = 0;
    pauseBG.zPosition = 2;
    [pauseBG runAction:[SKAction fadeAlphaTo:1 duration:duration / 2]];
    [self addChild:pauseBG];
}

这是辅助方法:

- (UIImage *)getBluredScreenshot {
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 1);
    [self.view drawViewHierarchyInRect:self.view.frame afterScreenUpdates:YES];
    UIImage *ss = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CIFilter *gaussianBlurFilter = [CIFilter filterWithName:@"CIGaussianBlur"];
    [gaussianBlurFilter setDefaults];
    [gaussianBlurFilter setValue:[CIImage imageWithCGImage:[ss CGImage]] forKey:kCIInputImageKey];
    [gaussianBlurFilter setValue:@10 forKey:kCIInputRadiusKey];

    CIImage *outputImage = [gaussianBlurFilter outputImage];
    CIContext *context   = [CIContext contextWithOptions:nil];
    CGRect rect          = [outputImage extent];
    rect.origin.x        += (rect.size.width  - ss.size.width ) / 2;
    rect.origin.y        += (rect.size.height - ss.size.height) / 2;
    rect.size            = ss.size;
    CGImageRef cgimg     = [context createCGImage:outputImage fromRect:rect];
    UIImage *image       = [UIImage imageWithCGImage:cgimg];
    CGImageRelease(cgimg);
    return image;
}

答案 3 :(得分:2)

这是在没有图层的情况下在swift 2中完成此操作的另一个示例:

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")

}))

}

答案 4 :(得分:2)

Swift 3更新:这是@Chuck Gaffney为Swift 3更新的答案。我知道这个问题被标记为objective-c,但是这个页面在Google中排名第二,因为“swift spritekit模糊”。我将 currentScene 更改为 self

    func getBluredScreenshot() -> SKSpriteNode{

    //create the graphics context
    UIGraphicsBeginImageContextWithOptions(CGSize(width: self.view!.frame.size.width, height: self.view!.frame.size.height), true, 1)

    self.view!.drawHierarchy(in: self.view!.frame, afterScreenUpdates: true)

    // retrieve graphics context
    _ = UIGraphicsGetCurrentContext()

    // query image from it
    let image = UIGraphicsGetImageFromCurrentImageContext()

    // create Core Image context
    let ciContext = CIContext(options: nil)
    // create a CIImage, think of a CIImage as image data for processing, nothing is displayed or can be displayed at this point
    let coreImage = CIImage(image: image!)
    // pick the filter we want
    let filter = CIFilter(name: "CIGaussianBlur")
    // pass our image as input
    filter?.setValue(coreImage, forKey: kCIInputImageKey)

    //edit the amount of blur
    filter?.setValue(3, forKey: kCIInputRadiusKey)

    //retrieve the processed image
    let filteredImageData = filter?.value(forKey: kCIOutputImageKey) as! CIImage
    // return a Quartz image from the Core Image context
    let filteredImageRef = ciContext.createCGImage(filteredImageData, from: filteredImageData.extent)
    // final UIImage
    let filteredImage = UIImage(cgImage: filteredImageRef!)

    // create a texture, pass the UIImage
    let texture = SKTexture(image: filteredImage)
    // wrap it inside a sprite node
    let sprite = SKSpriteNode(texture:texture)

    // make image the position in the center
    sprite.position = CGPoint(x: self.frame.midX, y: self.frame.midY)

    let scale:CGFloat = UIScreen.main.scale

    sprite.size.width  *= scale

    sprite.size.height *= scale

    return sprite


}

func loadPauseBGScreen(){

    let duration = 1.0

    let pauseBG:SKSpriteNode = self.getBluredScreenshot()

    pauseBG.alpha = 0
    pauseBG.zPosition = self.zPosition + 1
    pauseBG.run(SKAction.fadeAlpha(to: 1, duration: duration))

    self.addChild(pauseBG)

}

答案 5 :(得分:2)

Swift 4:

如果你想模糊场景中的所有内容,请将它添加到你的gameScene中:

let  blur = CIFilter(name:"CIGaussianBlur",withInputParameters: ["inputRadius": 10.0])
        self.filter = blur
        self.shouldRasterize = true
        self.shouldEnableEffects = false

如果要使用它,请更改self.shouldEnableEffects = true。

答案 6 :(得分:0)

我现在正在尝试在2020年5月(Xcode 11和iOS 13.x)做同样的事情,但是并不能“动画化”模糊半径。就我而言,我从场景完全模糊开始,然后逐渐“取消模糊”(将inputRadius设置为0)。

以某种方式,在自定义动作块中设置的新输入半径值未反映在渲染的场景中。我的代码如下:

    private func unblur() {
        run(SKAction.customAction(withDuration: unblurDuration, actionBlock: { [weak self] (_, elapsed) in
            guard let this = self else { return }
            let ratio = (TimeInterval(elapsed) / this.unblurDuration)
            let radius = this.maxBlurRadius * (1 - ratio) // goes to 0 as ratio goes to 1
            this.filter?.setValue(radius, forKey: kCIInputRadiusKey)
        }))
    }

我什至尝试使用SKScene.update(_:)和一些用于记时的变量手动更新值,但结果相同。

我想到,如果我将模糊滤镜“重新声明”为我的SKScene的.filter属性,也许可以强制刷新(请参见代码结尾处所有大写的注释),同样的效果,而且有效。

完整代码:

class MyScene: SKScene {

    private let maxBlurRadius: Double = 50
    private let unblurDuration: TimeInterval = 5

    init(size: CGSize) {
        super.init(size: size)

        let filter = CIFilter(name: "CIGaussianBlur")
        filter?.setValue(maxBlurRadius, forKey: kCIInputRadiusKey)
        self.filter = filter
        self.shouldEnableEffects = true
        self.shouldRasterize = false

        // (...rest of the child nodes, etc...)

    }

    override func didMove(to view: SKView) {
        super.didMove(to: view)
        self.unblur()
    }

    private func unblur() {
        run(SKAction.customAction(withDuration: unblurDuration, actionBlock: { [weak self] (_, elapsed) in
            guard let this = self else { return }
            let ratio = (TimeInterval(elapsed) / this.unblurDuration)
            let radius = this.maxBlurRadius * (1 - ratio) // goes to 0 as ratio goes to 1

            // OBTAIN THE FILTER
            let filter = this.filter

            // MODIFY ATTRIBUTE 
            filter?.setValue(radius, forKey: kCIInputRadiusKey)

            // RE=ASSIGN TO SCENE
            this.filter = filter
        }))
    }
}

我希望这对某人有帮助!

相关问题