问题
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?
回答1:
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)
回答2:
This is in addition to @PranavKasetti answer.
In Swift 4.2, if you want to save a SKTexture to a file in your Mac (and maybe add the file to your project) here is a quick solution:
func saveTexture(){
print("Saving Texture to Mac Desktop")
let noiseMap = scene!.noiseMap! // Reference to the node you want to save
let noiseTexture = SKTexture(noiseMap: noiseMap)
let cgNoise = noiseTexture.cgImage()
let imageRep = NSBitmapImageRep(cgImage: cgNoise)
let imData = imageRep.representation(using: .png, properties: [:])
let fileManager = FileManager.default
let urls = fileManager.urls(for: .desktopDirectory, in: .userDomainMask).first!
if let theData = imData{
do{
try theData.write(to: urls.appendingPathComponent("SavedNoise.png"))
}catch{
print("COULD NOT SAVE")
}
}
}
来源:https://stackoverflow.com/questions/47495650/how-to-save-skspritenode-as-png-image-to-camera-roll