Loading...

How to convert Color type to hex and vice-versa while retaining alpha information?

question swiftui swift
Ram Patra Published on October 30, 2023

The below should work both on macOS and iOS with one minor change. That is, use UIColor instead of NSColor if you’re planning to use it for iOS.

import SwiftUI

extension Color {
    init(hex: String) {
        var hexSanitized = hex.trimmingCharacters(in: .whitespacesAndNewlines)
        hexSanitized = hexSanitized.replacingOccurrences(of: "#", with: "")

        var rgb: UInt64 = 0

        Scanner(string: hexSanitized).scanHexInt64(&rgb)

        let red = Double((rgb & 0xFF000000) >> 24) / 255.0
        let green = Double((rgb & 0x00FF0000) >> 16) / 255.0
        let blue = Double((rgb & 0x0000FF00) >> 8) / 255.0
        let alpha = Double(rgb & 0x000000FF) / 255.0
        
        self.init(.sRGB, red: red, green: green, blue: blue, opacity: alpha)
    }

    var hex: String {
        if let nsColor = NSColor(self).usingColorSpace(.sRGB) {
            let red = Int(nsColor.redComponent * 255)
            let green = Int(nsColor.greenComponent * 255)
            let blue = Int(nsColor.blueComponent * 255)
            let alpha = Int(nsColor.alphaComponent * 255)

            return String(format: "#%02X%02X%02X%02X", red, green, blue, alpha)
        } else {
            // Default to .gray color if NSColor conversion fails
            return "#8e8e93ff"
        }
    }
}

You can then use it like below:

var someColor: Color = Color(hex: "#FFFFFFFF") // white color with 100% opacity
var someColorHex: String = someColor.hex // white color in hexadecimal format
Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on October 30, 2023
Image placeholder

Keep reading

If this article was helpful, others might be too

question swiftui macos September 3, 2024 How to open and close windows programmatically in SwiftUI?

To open or close a window programmatically from outside that window using environment variables, you need to leverage the new openWindow (macOS 13+) and dismissWindow (macOS 14+) environment variables. This environment variables allow you to programmatically open and close a window by its identifier.

question swiftui swift September 30, 2023 How to open the Settings view in a SwiftUI app on macOS 14.0 (Sonoma)?

In macOS 14.0 (Sonoma), Apple removed support for NSApp.sendAction to open the Settings view in your SwiftUI app. You now have to use SettingsLink like below:

question swiftui March 29, 2024 How to group different style modifiers and reuse them across multiple SwiftUI views?

In SwiftUI, you can create custom view modifiers to encapsulate common styling configurations and reuse them across different views. Here’s how you can create and reuse a custom view modifier: