From b144bfd6df47a49f80022e52058c1e7023d5d578 Mon Sep 17 00:00:00 2001 From: Siddhant Mehta Date: Sun, 23 Feb 2025 15:18:58 +0530 Subject: [PATCH] Add string utils for Color --- .../Platform/SwiftUI/Color+ColorSpaces.swift | 6 --- .../Platform/SwiftUI/Color+Strings.swift | 46 +++++++++++++++++++ 2 files changed, 46 insertions(+), 6 deletions(-) create mode 100644 Sources/ColorTokensKit/Platform/SwiftUI/Color+Strings.swift diff --git a/Sources/ColorTokensKit/Platform/SwiftUI/Color+ColorSpaces.swift b/Sources/ColorTokensKit/Platform/SwiftUI/Color+ColorSpaces.swift index 2034a37..c122e15 100644 --- a/Sources/ColorTokensKit/Platform/SwiftUI/Color+ColorSpaces.swift +++ b/Sources/ColorTokensKit/Platform/SwiftUI/Color+ColorSpaces.swift @@ -25,10 +25,4 @@ public extension Color { func toXYZ() -> XYZColor { RGBColor(color: self).toXYZ() } - - /// Get LCH string representation - func getLCHString() -> String { - let lchColor = LCHColor(color: self) - return "L:\(Int(lchColor.l)) C:\(Int(lchColor.c)) H:\(Int(lchColor.h))" - } } diff --git a/Sources/ColorTokensKit/Platform/SwiftUI/Color+Strings.swift b/Sources/ColorTokensKit/Platform/SwiftUI/Color+Strings.swift new file mode 100644 index 0000000..8ed4301 --- /dev/null +++ b/Sources/ColorTokensKit/Platform/SwiftUI/Color+Strings.swift @@ -0,0 +1,46 @@ +// +// LCH+Utils.swift +// ColorTokensKit +// +// Created by Siddhant Mehta on 2025-02-23. +// + +import SwiftUI + +public extension Color { + + /// Converts the `LCHColor` to a hexadecimal string representation. + public func getHexString() -> String { + let resolvedColor = resolve(in: .init()) + + // Ensure RGB values are within [0, 1] + let r = Double(max(0, min(resolvedColor.red, 1))) + let g = Double(max(0, min(resolvedColor.green, 1))) + let b = Double(max(0, min(resolvedColor.blue, 1))) + let a = Double(max(0, min(resolvedColor.cgColor.alpha, 1))) + + // Convert to hexadecimal + let hexString: String + if a != 1.0 { + hexString = String(format: "%02lX%02lX%02lX%02lX", lround(r * 255), lround(g * 255), lround(b * 255), lround(a * 255)) + } else { + hexString = String(format: "%02lX%02lX%02lX", lround(r * 255), lround(g * 255), lround(b * 255)) + } + + print("red \(r)") + print("green \(g)") + print("blue \(b)") + print("alpha \(a)") + print("hex: \(hexString)") + print("-------") + + return hexString + } + + /// Get LCH string representation + public func getLCHString() -> String { + let lchColor = LCHColor(color: self) + return "L:\(Int(lchColor.l)) C:\(Int(lchColor.c)) H:\(Int(lchColor.h))" + } + +}