multithreading - 更改后台线程上 SKSpriteNode 纹理的色调

标签 multithreading swift sprite-kit core-graphics

我正在更改我正在编写的游戏中的一些 Sprite 的色调。色调改变函数是 -

private func image(fromOriginalImage image: UIImage, withHue hue: CGFloat) -> UIImage
{
    let rect = CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: image.size)

    UIGraphicsBeginImageContext(image.size)

    let context = UIGraphicsGetCurrentContext()

    CGContextTranslateCTM(context, 0.0, image.size.height)
    CGContextScaleCTM(context, 1.0, -1.0)

    CGContextDrawImage(context, rect, image.CGImage)

    CGContextSetBlendMode(context, CGBlendMode.Hue)

    CGContextClipToMask(context, rect, image.CGImage) 
    CGContextSetFillColorWithColor(context, UIColor(hue: hue, saturation: 0.5, brightness: 0.4, alpha: 1.0).CGColor)
    CGContextFillRect(context, rect)

    let colouredImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()


    return colouredImage
}

这在后台线程上运行良好,然后我将它返回的图像返回到主线程以更新 SKSpriteNode 的纹理,有时我会在游戏中遇到明显的卡顿 -

GCD.async
{
    if let colouredImage = self.image(fromOriginalImage: image, withHue: hue)
    {
        GCD.async_main
        {
            self.texture = SKTexture(image: colouredImage)
        }
    }
}

如果有人有任何建议如何做得更好,我会非常高兴。

谢谢

最佳答案

修复方法是将纹理更改放入 SKAction -

GCD.async
{
    if let colouredImage = self.image(fromOriginalImage: image, withHue: hue)
    {
        let changeTexture = SKAction.setTexture(SKTexture(image: colouredImage))
        self.runAction(changeTexture)
    }
}

spriteKit 引擎会在自己的时间内处理它...

关于multithreading - 更改后台线程上 SKSpriteNode 纹理的色调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33594239/

相关文章:

swift - SKEmitterNode 在场景重启时导致崩溃

c++ - 如何维护对另一个类中元素的线程安全引用

c - 关于 pthread_create() 和 pthread_join()

ios - 以编程方式全屏打开 iframe 视频

ios - 当json包含没有键的数组时如何检查swiftyJSON中是否存在键

ios - 不使用 UIApplication.shared 获取状态栏的大小

swift - SpriteKit : stuck trying to use SKNode. contains() 缩放 Sprite

multithreading - akka 线程在应用程序空闲时使用 100% CPU

c# - 结果导致任务死锁

ios - 如何将 SKScene 添加到 SCNNode 平面?