如何使sprite节点的纹理变暗

时间:2017-07-27 15:31:14

标签: ios swift sprite-kit

我有以下代码,我在其中创建一个显示动画GIF的精灵节点。我想创建另一个函数,在调用时使GIF变暗。我仍然可以观看动画,但内容会明显变暗。我不确定如何处理这个问题。我是否应该单独使用于创建动画的每个纹理或框架变暗?如果是这样,我如何在第一个地方使纹理或框架变暗?

    // Extract frames and duration
    guard let imageData = try? Data(contentsOf: url as URL) else {
        return 
    }
    let source = CGImageSourceCreateWithData(imageData as CFData, nil)
    var images = [CGImage]()
    let count = CGImageSourceGetCount(source!)
    var delays = [Int]()
    // Fill arrays
    for i in 0..<count {
        // Add image
        if let image = CGImageSourceCreateImageAtIndex(source!, i, nil) {
            images.append(image)
        }

        // At it's delay in cs
        let delaySeconds = UIImage.delayForImageAtIndex(Int(i),
                                                        source: source)
        delays.append(Int(delaySeconds * 1000.0)) // Seconds to ms
    }

    // Calculate full duration
    let duration: Int = {
        var sum = 0

        for val: Int in delays {
            sum += val
        }

        return sum
    }()

    // Get frames
    let gcd = SKScene.gcdForArray(delays)
    var frames = [SKTexture]()

    var frame: SKTexture
    var frameCount: Int
    for i in 0..<count {
        frame = SKTexture(cgImage: images[Int(i)])
        frameCount = Int(delays[Int(i)] / gcd)

        for _ in 0..<frameCount {
            frames.append(frame)
        }
    }


    let gifNode = SKSpriteNode.init(texture: frames[0])
    gifNode.position = CGPoint(x: skScene.size.width / 2.0, y: skScene.size.height / 2.0)
    gifNode.name = "content"


    // Add animation 
    let gifAnimation = SKAction.animate(with: frames, timePerFrame: ((Double(duration) / 1000.0)) / Double(frames.count))
    gifNode.run(SKAction.repeatForever(gifAnimation))
    skScene.addChild(gifNode)

1 个答案:

答案 0 :(得分:0)

我建议使用colorize(with:colorBlendFactor:duration:)方法。它是一个动画,可以动画改变整个节点的颜色。这样你就不必使个别纹理或框架变暗,并且它还增加了从非暗色到暗色的良好过渡。一旦动作结束,节点将保持变暗,直到你取消它为止,因此对节点的纹理的任何更改也将作为暗色显示给用户。

选择任何颜色和颜色,最适合您的颜色,以获得所需的暗色效果,例如:您可以将color设置为.black,将colorBlendFactor设置为0.3。要取消标记,只需将颜色设置为.clearcolorBlendFactor为0。

文档here

希望这有帮助!