Skip to content

Instantly share code, notes, and snippets.

@J0ker98
Created November 12, 2020 21:53
Show Gist options
  • Save J0ker98/4f14b97c397df75906f4eefcf553df3f to your computer and use it in GitHub Desktop.
Save J0ker98/4f14b97c397df75906f4eefcf553df3f to your computer and use it in GitHub Desktop.
Swift 5 UIImage white background removal
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