Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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))
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement