Created
November 12, 2020 21:53
-
-
Save J0ker98/4f14b97c397df75906f4eefcf553df3f to your computer and use it in GitHub Desktop.
Swift 5 UIImage white background removal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension UIImage { | |
func removeBackground() -> UIImage? { | |
if let rawImageRef = self.cgImage { | |
let colorMasking: [CGFloat] = [200, 255, 200, 255, 200, 255] | |
UIGraphicsBeginImageContext(self.size) | |
if let maskedImageRef = rawImageRef.copy(maskingColorComponents: colorMasking) { | |
UIGraphicsGetCurrentContext()!.translateBy(x: 0.0, y: self.size.height) | |
UIGraphicsGetCurrentContext()!.scaleBy(x: 1.0, y: -1.0) | |
UIGraphicsGetCurrentContext()!.draw(maskedImageRef, in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)) | |
let result = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
return result | |
} | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment