Search code examples
swiftcalayer

Saving multi layer CALayer image to Library?


So I got a view with a layer and some sublayer that have compositingFilter set with blend modes to see though the layers. I want to save all sublayer to one image in the photo library. Everything looks good in the views but when I save the CALayer, by converting it to a UIImage with UIGraphicsContext and using UIImageWriteToSavedPhotosAlbum, I only get one layer saved.

Dose anyone know how to convert multiple sublayers in a CALayer to a UIImage?


Solution

  • Had the same problem with you, I added many sublayers to a CALayer of UIImageView by imageView.layer.addSublayer(newLayer).

    Solved it by following other's instructions. Hope my code could give any idea.

    @IBAction func saveArtwork(_ sender: Any) {
    
        UIGraphicsBeginImageContext(self.imageView.bounds.size)
    
        // The code below may solve your problem
        imageView.layer.render(in: UIGraphicsGetCurrentContext()!)
    
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    
        let activity = UIActivityViewController(activityItems: [image!], applicationActivities: nil)
        present(activity, animated: true, completion: nil)
    }