How can I make that an object of the same class become the return value of initializer?

北慕城南 提交于 2019-12-04 06:16:14

问题


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?


回答1:


As the error states UIImage is immutable. What you can do is to get a CGImage from your outputImage and use UIImage init(cgImage: CGImage) initializer to initialize a new image from it:

extension UIImage {
    convenience init?(layer: CALayer) {
        UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, 0)
        defer { UIGraphicsEndImageContext() }
        guard let context = UIGraphicsGetCurrentContext() else {
            return nil
        }
        layer.render(in: context)
        guard let outputImage = UIGraphicsGetImageFromCurrentImageContext()?.cgImage else {
            return nil
        }
        self.init(cgImage: outputImage)
    }
}


来源:https://stackoverflow.com/questions/48698190/how-can-i-make-that-an-object-of-the-same-class-become-the-return-value-of-initi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!