iosswiftuiimagepngcamera-roll

How to save SKSpriteNode as PNG image to Camera Roll?


I'm trying to convert SKSpriteNode as a PNG image with transparency to Camera Roll.

This saves the image but not with transparency:

let image = UIImage(cgImage: (spriteNode.texture?.cgImage())!)
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

This complains:

Cannot convert value of type 'Data?' to expected argument type 'UIImage'

let image = UIImage(cgImage: (createdCloudShadow.texture?.cgImage())!)
let image2 = UIImagePNGRepresentation(image)
UIImageWriteToSavedPhotosAlbum(image2, nil, nil, nil)

How can I save SKSpriteNode as PNG to camera Roll?


Solution

  • The UIImagePNGRepresentation(_:) function returns Data? as can be seen from the documentation.

    So you probably just need to rewrite as follows:

    let image = UIImage(cgImage: (createdCloudShadow.texture?.cgImage())!)
    let imData = UIImagePNGRepresentation(image)
    let image2 = UIImage(data: imData)
    UIImageWriteToSavedPhotosAlbum(image2, nil, nil, nil)