From Hex to Color and Back in SwiftUI

PHOTO EMBED

Wed Aug 10 2022 08:11:11 GMT+0000 (Coordinated Universal Time)

Saved by @Nerkyator #ios #swiftui

import SwiftUI
import UIKit

extension Color {
    func toHex() -> String? {
        let uic = UIColor(self)
        guard let components = uic.cgColor.components, components.count >= 3 else {
            return nil
        }
        let r = Float(components[0])
        let g = Float(components[1])
        let b = Float(components[2])
        var a = Float(1.0)

        if components.count >= 4 {
            a = Float(components[3])
        }

        if a != Float(1.0) {
            return String(format: "%02lX%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255), lroundf(a * 255))
        } else {
            return String(format: "%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255))
        }
    }
}
content_copyCOPY

https://blog.eidinger.info/from-hex-to-color-and-back-in-swiftui