如何将 SKSpriteNode 保存为 PNG 图像到相机胶卷?
How to save SKSpriteNode as PNG image to Camera Roll?
我正在尝试将 SKSpriteNode 转换为具有透明度的 PNG 图像到相机胶卷。
这会保存图像但不带透明度:
let image = UIImage(cgImage: (spriteNode.texture?.cgImage())!)
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
这抱怨:
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)
如何将 SKSpriteNode 保存为 PNG 格式到相机胶卷?
UIImagePNGRepresentation(_:)
函数returnsData?
可以看出documentation.
所以你可能只需要重写如下:
let image = UIImage(cgImage: (createdCloudShadow.texture?.cgImage())!)
let imData = UIImagePNGRepresentation(image)
let image2 = UIImage(data: imData)
UIImageWriteToSavedPhotosAlbum(image2, nil, nil, nil)
这是@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")
}
}
}
我正在尝试将 SKSpriteNode 转换为具有透明度的 PNG 图像到相机胶卷。
这会保存图像但不带透明度:
let image = UIImage(cgImage: (spriteNode.texture?.cgImage())!)
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
这抱怨:
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)
如何将 SKSpriteNode 保存为 PNG 格式到相机胶卷?
UIImagePNGRepresentation(_:)
函数returnsData?
可以看出documentation.
所以你可能只需要重写如下:
let image = UIImage(cgImage: (createdCloudShadow.texture?.cgImage())!)
let imData = UIImagePNGRepresentation(image)
let image2 = UIImage(data: imData)
UIImageWriteToSavedPhotosAlbum(image2, nil, nil, nil)
这是@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")
}
}
}