SHARE
TWEET

Untitled

a guest Apr 21st, 2019 83 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. extension UIImage {
  2.     func replaceColor(_ color: UIColor, with: UIColor) -> UIImage? {
  3.         guard let fromRGB = color.rgb(), let toRGB = with.rgb() else { return self }
  4.        
  5.         let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
  6.         UIGraphicsBeginImageContextWithOptions(rect.size, false, self.scale)
  7.         UIRectFill(rect)
  8.         draw(in: rect, blendMode: .copy, alpha: 1)
  9.        
  10.         guard let contextRef = UIGraphicsGetCurrentContext() else { return self }
  11.         var data = contextRef.data?.assumingMemoryBound(to: UInt8.self)
  12.         if data == nil { return self }
  13.        
  14.         let bytesPerRow = contextRef.bytesPerRow
  15.         let rowsCount = contextRef.height
  16.         let pEnd = data! + (bytesPerRow * rowsCount)
  17.        
  18.         while data! < pEnd {
  19.             if data![0] == fromRGB.b && data![1] == fromRGB.g && data![2] == fromRGB.r {
  20.                 data![0] = toRGB.b
  21.                 data![1] = toRGB.g
  22.                 data![2] = toRGB.r
  23.             }
  24.             data! += 4
  25.         }
  26.        
  27.         let newImage = UIGraphicsGetImageFromCurrentImageContext()
  28.         UIGraphicsEndImageContext()
  29.         return newImage
  30.     }
  31. }
  32.  
  33. private extension UIColor {
  34.     func rgb() -> (r: UInt8, g: UInt8, b: UInt8)? {
  35.         var fRedComp: CGFloat = 0, fGreenComp: CGFloat = 0, fBlueComp: CGFloat = 0, fAlpha: CGFloat = 0
  36.         guard self.getRed(&fRedComp, green: &fGreenComp, blue: &fBlueComp, alpha: &fAlpha) else { return nil }
  37.         return (r: UInt8(fRedComp * 255), g: UInt8(fGreenComp * 255), b: UInt8(fBlueComp * 255))
  38.     }
  39. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top