I have this function:
extension UIImage {
static func from(layer: CALayer) -> UIImage? {
UIGraphicsBeginImageContext(layer.frame.size)
layer.render(in: UIGraphicsGetCurrentContext()!)
let outputImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return outputImage
}
}
How can I change it into like this?
extension UIImage {
convenience init(layer: CALayer) {
self.init();
UIGraphicsBeginImageContext(layer.frame.size)
layer.render(in: UIGraphicsGetCurrentContext()!)
let outputImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self = outputImage; // Error: cannot assign to self: self is immutable
}
}
I want that the result of UIGraphicsGetImageFromCurrentImageContext() becomes the initiated "self". But the result is already a UIImage. I don't suppose I should use "mutating" in this function?
As the error states
UIImageis immutable. What you can do is to get aCGImagefrom your outputImage and useUIImageinit(cgImage: CGImage)initializer to initialize a new image from it: