Skip to content

Instantly share code, notes, and snippets.

@Kievkao
Created April 11, 2019 08:27
Show Gist options
  • Save Kievkao/3f40262a43a855517edec2b3cc9e7c29 to your computer and use it in GitHub Desktop.
Save Kievkao/3f40262a43a855517edec2b3cc9e7c29 to your computer and use it in GitHub Desktop.
Replace pixels in UIImage (white or black. For other colours require some adjustment in terms of CGFloat converting)
extension UIImage {
func replaceColor(_ color: UIColor, with: UIColor) -> UIImage? {
guard let fromRGB = color.rgb(), let toRGB = with.rgb() else { return self }
let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
UIGraphicsBeginImageContextWithOptions(rect.size, false, self.scale)
UIRectFill(rect)
draw(in: rect, blendMode: .copy, alpha: 1)
guard let contextRef = UIGraphicsGetCurrentContext() else { return self }
var data = contextRef.data?.assumingMemoryBound(to: UInt8.self)
if data == nil { return self }
let bytesPerRow = contextRef.bytesPerRow
let rowsCount = contextRef.height
let pEnd = data! + (bytesPerRow * rowsCount)
while data! < pEnd {
if data![0] == fromRGB.b && data![1] == fromRGB.g && data![2] == fromRGB.r {
data![0] = toRGB.b
data![1] = toRGB.g
data![2] = toRGB.r
}
data! += 4
}
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
private extension UIColor {
func rgb() -> (r: UInt8, g: UInt8, b: UInt8)? {
var fRedComp: CGFloat = 0, fGreenComp: CGFloat = 0, fBlueComp: CGFloat = 0, fAlpha: CGFloat = 0
guard self.getRed(&fRedComp, green: &fGreenComp, blue: &fBlueComp, alpha: &fAlpha) else { return nil }
return (r: UInt8(fRedComp * 255), g: UInt8(fGreenComp * 255), b: UInt8(fBlueComp * 255))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment