1

I'm having so many problems with SKTextureAtlas I wonder whether it's worth persevering with. It seems to be broken on the simulator, but I'm also running into issues with it on device.

My aim is to be able to generate - and save to device for retrieval the next time it starts up - custom texture atlases with procedurally generated images.

My 'save atlas' function iterates through the textures, retrieves them, and tries to save them as png files. It works fine with the original texture, but just saves a blank image with the retrieved texture. I have no idea why this should be. The following code illustrates the point if you place it in an SKScene:

        let label = SKLabelNode(text: "Hello World")
    let view = SKView()
    let texture = view.texture(from: label)!
    let cgImage = texture.cgImage()
    let uiImage = UIImage(cgImage: cgImage)
    
    let atlas = SKTextureAtlas(dictionary: ["hello":uiImage])
    let retrievedTex = atlas.textureNamed("hello")
    
    //       let pngData = uiImage.pngData()
    let pngData = UIImage(cgImage: (retrievedTex.cgImage())).pngData()
    //save the data
    guard let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { print("Failed to find document directory");return }
    let fileUrl = documentDirectoryUrl.appendingPathComponent("Hello.png")
    do {
        try pngData!.write(to: fileUrl)
    }
    catch {
        print("Failed to write PNG data: \(error.localizedDescription)")
    }
    // Load and display
    if let data = FileManager.default.contents(atPath: fileUrl.path) {
        guard let image = UIImage(data: data) else {return}
        let tex = SKTexture(image: image)
        let sprite = SKSpriteNode(texture: tex)
        addChild(sprite)
        sprite.position = CGPoint(x: UIScreen.main.bounds.width/2, y: UIScreen.main.bounds.height/2)
    }

This doesn't work at all on the simulator (which I've had to accept is a cgImage bug) but on the device it displays a distorted texture. You can see how it's meant to work if you swap the let pngData... line for the commented out version.

Is there anything I can do with the SKTextures I get back from an atlas to make them 'behave'?

Robin
  • 373
  • 1
  • 3
  • 20
Matthew R
  • 33
  • 8

0 Answers0