Avatar
public init(uiImage: UIImage) { func cgimage(from uiimage: UIImage) -> CGImage? { #if os(iOS) || os(tvOS) return uiimage.cgImage ?? { guard let ciImage = uiImage.ciImage else { return nil } let context = CIContext() guard let cgImage = context.createCGImage(ciImage, from: ciImage.extent) else { fatalError("Failed to create a `CGImage` from an internal `CIImage` object from this `UIImage` instance: \(uiImage)") } return cgImage }() #else return uiimage.cgImage #endif } if let cgImage = cgimage(from: uiImage) { self.init(cgImage: cgImage) } else { // This `gurad` can be replaced with `assert` if you are sure that the `size` is always equal to `.zero`. guard uiImage.size == .zero else { fatalError("The `size` of this `UIImage` instance (\(uiImage)) is not equal to `.zero` though both `cgImage` and `ciImage` of the instance are `nil`.") } self.init(width: 0, height: 0, pixels: []) } } (edited)