无法可靠地验证SKSpriteNode的纹理

时间:2015-02-07 18:51:32

标签: swift sprite-kit skspritenode sktexture

我正在尝试编写一个测试,用于验证场景中的SKSpriteNode是否具有正确的纹理。 测试看起来像这样:

let sceneSprite = scene.childNodeWithName("sceneSprite") as SKSpriteNode!

let sprite = SKSpriteNode(imageNamed: expectedSpriteTexture)
sprite.size = sceneSprite.size // 102.4 x 136.533

XCTAssertTrue(sceneSprite.texture!.sameAs(sprite.texture!), "Scene sprite has wrong texture")

SKTexture的 sameAs 方法通过以下扩展程序实现:

extension SKTexture {
    func sameAs(texture: SKTexture) -> Bool {
        return self.image.sameAs(texture.image)
    }

    var image: UIImage {
        let view = SKView(frame:CGRectMake(0, 0, size().width, size().height))
        let scene = SKScene(size: size())
        let sprite  = SKSpriteNode(texture: self)
        sprite.position = CGPoint(x: CGRectGetMidX(view.frame), y: CGRectGetMidY(view.frame))
        scene.addChild(sprite)
        view.presentScene(scene)
        return self.imageWithView(view)
    }

    func imageWithView(view: UIView) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0)
        view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

extension UIImage {
    func sameAs(image: UIImage) -> Bool {
        let firstData = UIImagePNGRepresentation(self);
        let secondData = UIImagePNGRepresentation(image);
        return firstData.isEqual(secondData)
    }
}

问题有时是测试通过,有时测试失败。我更改了代码,以便在失败时保存图像,并发现测试失败,因为即使第一张图像正确,第二张图像也完全是黑色。 可以做些什么,以便测试能够可靠地通过? 这种故障发生在iPad2的模拟器上。

1 个答案:

答案 0 :(得分:0)

我进行了以下更改,似乎可以使测试可靠地通过

func imageWithView(view: UIView) -> UIImage {
    UIGraphicsBeginImageContext(view.bounds.size)
    view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: false)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}

人们有什么想法可以让测试成功?