hex color converter

Hex Color Converter Convert HEX Strings to UIColor and Color in iOS Design

Color plays a crucial role in iOS design, as it has the power to evoke different emotions and impressions. The choice of color can make a design feel warm and inviting or cold and sterile. It can also convey a sense of modernity or outdatedness to the design. One critical aspect of color is transferring it to and from your iOS application with other applications and services. Currently, most applications transfer color using RGBA HEX strings. However, iOS does not have a built-in way to convert HEX strings to UIColor or SwiftUI’s Color types.

In this article, we will learn how to convert HEX strings to UIColor and Color for both UIKit and SwiftUI in iOS.

Converting HEX Strings to UIColor in UIKit

To convert HEX strings to UIColor in UIKit, follow these steps:

  1. Create a new Xcode project.
  2. Create a file called “UIColor+Hex.swift” and add the following code:

“`swift
extension UIColor {
convenience init?(hex: String) {
var hexString = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if hexString.hasPrefix(“#”) {
hexString.removeFirst()
}

    let scanner = Scanner(string: hexString)
    var rgbValue: UInt64 = 0
    guard scanner.scanHexInt64(&rgbValue) else { return nil }

    var red, green, blue, alpha: UInt64
    switch hexString.count {
    case 6:
        red = (rgbValue >> 16)
        green = (rgbValue >> 8) & 0xFF
        blue = (rgbValue) & 0xFF
        alpha = 255
    case 8:
        red = (rgbValue >> 16)
        green = (rgbValue >> 8) & 0xFF
        blue = (rgbValue) & 0xFF
        alpha = rgbValue >> 24
    default:
        return nil
    }

    self.init(red: CGFloat(red) / 255, green: CGFloat(green) / 255, blue: CGFloat(blue) / 255, alpha: CGFloat(alpha) / 255)
}

func toHexString(includeAlpha: Bool = false) -> String? {
    guard let components = self.cgColor.components else { return nil }

    let red = Int(components[0] * 255.0)
    let green = Int(components[1] * 255.0)
    let blue = Int(components[2] * 255.0)

    let hexString: String
    if includeAlpha, let alpha = components.last {
        let alphaValue = Int(alpha * 255.0)
        hexString = String(format: "#%02X%02X%02X%02X", red, green, blue, alphaValue)
    } else {
        hexString = String(format: "#%02X%02X%02X", red, green, blue)
    }

    return hexString
}

}
“`

  1. You can now use the UIColor extension to convert HEX strings to UIColor. For example:

swift
let hexString = "FF0000"
let uiColor: UIColor? = UIColor(hex: hexString)

This code snippet will convert the HEX string “FF0000” to a UIColor object.

  1. You can also convert a UIColor object back to a HEX string using the toHexString method. For example:

swift
let hexString: String? = uiColor?.toHexString()

This code snippet will convert the UIColor object back to the HEX string representation.

Converting HEX Strings to Color in SwiftUI

If you are working with SwiftUI, you can convert HEX strings to Color using the following steps:

  1. Create a file called “Color+Hex.swift” in your SwiftUI project and add the following code:

“`swift
import SwiftUI

extension Color {
init?(hex: String) {
guard let uiColor = UIColor(hex: hex) else { return nil }
self.init(uiColor: uiColor)
}

func toHexString(includeAlpha: Bool = false) -> String? {
    return UIColor(self).toHexString(includeAlpha: includeAlpha)
}

}
“`

  1. You can now use the Color extension to convert HEX strings to Color. For example:

swift
let hexString = "FF0000"
let color: Color? = Color(hex: hexString)

This code snippet will convert the HEX string “FF0000” to a Color object in SwiftUI.

  1. You can also convert a Color object back to a HEX string using the toHexString method. For example:

swift
let hexString: String? = color?.toHexString()

This code snippet will convert the Color object back to the HEX string representation.

Additional Features: Easy Extension Methods with DittoSwift

If you’re using DittoSwift in your project, you can take advantage of the following extension methods for UIColor and Color conversion:

  1. Create a file called “Ditto+ColorExtensions.swift” and add the following code:

“`swift
import SwiftUI
import DittoSwift

extension DittoDocumentPath {
func uiColorFromHexString() -> UIColor? {
guard let string = self.string else { return nil }
return UIColor(hex: string)
}

func colorFromHexString() -> Color? {
    guard let string = self.string else { return nil }
    return Color(hex: string)
}

}

extension DittoMutableDocumentPath {
func set(color: Color, includeAlpha: Bool = false, isDefault: Bool = false) {
self.set(color.toHexString(includeAlpha: includeAlpha))
}

func set(uiColor: UIColor, includeAlpha: Bool = false, isDefault: Bool = false) {
    self.set(uiColor.toHexString(includeAlpha: includeAlpha))
}

func uiColorFromHexString() -> UIColor? {
    guard let string = self.string else { return nil }
    return UIColor(hex: string)
}

func colorFromHexString() -> Color? {
    guard let string = self.string else { return nil }
    return Color(hex: string)
}

}
“`

  1. Now, you can parse the DittoDocumentPath and DittoMutableDocumentPath objects to convert HEX strings to UIColor and Color, respectively. For example:

“`swift
let docs = ditto.store[“cars”].find(“make == $args.make”, args: [“make”: “Honda”]).exec()

docs.forEach { doc in
let uiColor: UIColor? = doc[“color”].uiColorFromHexString()
let color: Color? = doc[“color”].colorFromHexString()
}
“`

In this code snippet, we are retrieving documents from the “cars” collection and converting the “color” field from HEX strings to UIColor and Color objects.

  1. You can also mutate the DittoMutableDocumentPath with UIColor and Color extensions. For example:

swift
ditto.store["cars"].find("make == $args.make", args: ["make": "Honda"])
.update { mutableDoc in
mutableDoc["color"].set(Color.red)
}

This code snippet updates the “color” field of the documents with the UIColor object representing the color red.

Conclusion

Color is a vital part of any iOS app, and being able to convert between HEX strings and UIColor/Color is essential, especially when transmitting color through a network. By using the provided extensions, you can easily convert HEX strings to UIColor and Color in both UIKit and SwiftUI. Additionally, if you’re using DittoSwift, you can take advantage of the extension methods to simplify the conversion process. We hope this tutorial helps you in your next iOS project, whether you’re using Ditto or not!


In summary, this article discussed the importance of color in iOS design and the need to convert HEX strings to UIColor and Color in UIKit and SwiftUI. It provided step-by-step instructions and code snippets for converting HEX strings to UIColor and Color. It also introduced additional features using DittoSwift for easier conversion and mutation of UIColor and Color objects. By following these guidelines, you can seamlessly integrate color conversion into your iOS applications.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *