Last active
February 18, 2022 11:29
-
-
Save vitsky91/44b9519d800add412ece727962483cde to your computer and use it in GitHub Desktop.
Extension for UIColor: - init from String hex, - get hex String from Color, - init from Int values, - create image from UIColor
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
import UIKit | |
extension UIColor { | |
/// Creates image from color | |
/// - Parameter size: size of returned image | |
/// - Returns: UIImage | |
func image(_ size: CGSize = CGSize(width: 1, height: 1)) -> UIImage { | |
return UIGraphicsImageRenderer(size: size).image { rendererContext in | |
self.setFill() | |
rendererContext.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height)) | |
} | |
} | |
func hexStringFromColor() -> String { | |
let components = self.cgColor.components | |
let r: CGFloat = components?[0] ?? 0.0 | |
let g: CGFloat = components?[1] ?? 0.0 | |
let b: CGFloat = components?[2] ?? 0.0 | |
let hexString = String.init(format: "#%02lX%02lX%02lX", lroundf(Float(r * 255)), lroundf(Float(g * 255)), lroundf(Float(b * 255))) | |
return hexString | |
} | |
// MARK: - init | |
public convenience init(rgbColorCodeRed red: Int, green: Int, blue: Int, alpha: CGFloat) { | |
let redPart: CGFloat = CGFloat(red) / 255 | |
let greenPart: CGFloat = CGFloat(green) / 255 | |
let bluePart: CGFloat = CGFloat(blue) / 255 | |
self.init(red: redPart, green: greenPart, blue: bluePart, alpha: alpha) | |
} | |
public convenience init?(hex: String) { | |
let r, g, b, a: CGFloat | |
if hex.hasPrefix("#") { | |
let start = hex.index(hex.startIndex, offsetBy: 1) | |
let hexColor = String(hex[start...]) | |
if hexColor.count == 8 { | |
let scanner = Scanner(string: hexColor) | |
var hexNumber: UInt64 = 0 | |
if scanner.scanHexInt64(&hexNumber) { | |
r = CGFloat((hexNumber & 0xff000000) >> 24) / 255 | |
g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255 | |
b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255 | |
a = CGFloat(hexNumber & 0x000000ff) / 255 | |
self.init(red: r, green: g, blue: b, alpha: a) | |
return | |
} | |
} | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment