我正在尝试将SKSpriteNode转换为具有透明度的PNG图像到相机胶卷。
这样可以保存图像,但不保存透明度:
let image = UIImage(cgImage: (spriteNode.texture?.cgImage())!)
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
抱怨:
无法转换'数据'类型的值?期望参数类型'UIImage'
let image = UIImage(cgImage: (createdCloudShadow.texture?.cgImage())!)
let image2 = UIImagePNGRepresentation(image)
UIImageWriteToSavedPhotosAlbum(image2, nil, nil, nil)
如何将SKSpriteNode保存为PNG到相机滚动?
答案 0 :(得分:2)
从documentation可以看到UIImagePNGRepresentation(_:)
函数返回Data?
。
所以你可能只需要重写如下:
let image = UIImage(cgImage: (createdCloudShadow.texture?.cgImage())!)
let imData = UIImagePNGRepresentation(image)
let image2 = UIImage(data: imData)
UIImageWriteToSavedPhotosAlbum(image2, nil, nil, nil)
答案 1 :(得分:0)
这是@PranavKasetti答案的补充。
在Swift 4.2中,如果要将SKTexture保存到Mac中的文件中(并且可以将文件添加到项目中),这是一种快速解决方案:
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")
}
}
}