How to Convert Uicolor Value to a Named Color String

How to convert UIColor value to a named color string?

What do you want to do that for? Have a look at generic -desciption method for a start

UIColor* someColor = ...//Initialize color
NSString* colorString = [someColor description];

How to convert standard color names in string to UIColor values

There is no built in feature to make a UIColor with a name. You can write an extension like the one by Paul Hudson found here: https://www.hackingwithswift.com/example-code/uicolor/how-to-convert-a-html-name-string-into-a-uicolor

Simplified example:

extension UIColor {
public func named(_ name: String) -> UIColor? {
let allColors: [String: UIColor] = [
"red": .red,
]
let cleanedName = name.replacingOccurrences(of: " ", with: "").lowercased()
return allColors[cleanedName]
}
}

And then use it:

let redColor = UIColor().named("red")

You could also define an xcassets like in this article: https://medium.com/bobo-shone/how-to-use-named-color-in-xcode-9-d7149d270a16

And then use UIColor(named: "red")

How to convert UIColor to HEX and display in NSLog

Swift 5:

func hexStringFromColor(color: UIColor) -> String {
let components = color.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)))
print(hexString)
return hexString
}

func colorWithHexString(hexString: String) -> UIColor {
var colorString = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
colorString = colorString.replacingOccurrences(of: "#", with: "").uppercased()

print(colorString)
let alpha: CGFloat = 1.0
let red: CGFloat = self.colorComponentFrom(colorString: colorString, start: 0, length: 2)
let green: CGFloat = self.colorComponentFrom(colorString: colorString, start: 2, length: 2)
let blue: CGFloat = self.colorComponentFrom(colorString: colorString, start: 4, length: 2)

let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
return color
}

func colorComponentFrom(colorString: String, start: Int, length: Int) -> CGFloat {

let startIndex = colorString.index(colorString.startIndex, offsetBy: start)
let endIndex = colorString.index(startIndex, offsetBy: length)
let subString = colorString[startIndex..<endIndex]
let fullHexString = length == 2 ? subString : "\(subString)\(subString)"
var hexComponent: UInt32 = 0

guard Scanner(string: String(fullHexString)).scanHexInt32(&hexComponent) else {
return 0
}
let hexFloat: CGFloat = CGFloat(hexComponent)
let floatValue: CGFloat = CGFloat(hexFloat / 255.0)
print(floatValue)
return floatValue
}

How to use

let red =  CGFloat(30.0)
let green = CGFloat(171.0)
let blue = CGFloat(13.0)
let alpha = CGFloat(1.0)

let color = UIColor(red: CGFloat(red/255.0), green: CGFloat(green/255.0), blue: CGFloat(blue / 255.0), alpha: alpha)
let colorCode = self.hexStringFromColor(color: color)
print(colorCode)

let resultColor = self.colorWithHexString(hexString: colorCode)
print(resultColor)

Objective-C:

- (NSString *)hexStringFromColor:(UIColor *)color {
const CGFloat *components = CGColorGetComponents(color.CGColor);

CGFloat r = components[0];
CGFloat g = components[1];
CGFloat b = components[2];

return [NSString stringWithFormat:@"#%02lX%02lX%02lX",
lroundf(r * 255),
lroundf(g * 255),
lroundf(b * 255)];
}

After getting hex code string, Call below method to get UIColor

- (UIColor *) colorWithHexString: (NSString *) hexString
{
NSString *colorString = [[hexString stringByReplacingOccurrencesOfString: @"#" withString: @""] uppercaseString];

NSLog(@"colorString :%@",colorString);
CGFloat alpha, red, blue, green;

// #RGB
alpha = 1.0f;
red = [self colorComponentFrom: colorString start: 0 length: 2];
green = [self colorComponentFrom: colorString start: 2 length: 2];
blue = [self colorComponentFrom: colorString start: 4 length: 2];

return [UIColor colorWithRed: red green: green blue: blue alpha: alpha];
}

- (CGFloat) colorComponentFrom: (NSString *) string start: (NSUInteger) start length: (NSUInteger) length {
NSString *substring = [string substringWithRange: NSMakeRange(start, length)];
NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring];
unsigned hexComponent;
[[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent];
return hexComponent / 255.0;
}

How to use

// ( R = 30, G = 171, B = 13)? 
CGFloat red = 30.0;
CGFloat green = 171.0;
CGFloat blue = 13.0;
CGFloat alpha = 255.0
UIColor *color = [UIColor colorWithRed:(red/255.0) green:(green/255.0) blue:(blue/255.0) alpha:(alpha/255.0)];
NSString *colorCode = [self hexStringFromColor:color];
NSLog(@"Color Code: %@", colorCode);

UIColor *resultColor = [self colorWithHexString:colorCode];

How to convert from UIColor to string and string to UIColor in Xamarin.Ios using c#

First store color in DB as UIColor like this

 string color = yourBtn.BackgroundColor.ToString();

Then convert your color to UIColor as

 string hex = color.;
nfloat red = Convert.ToInt32(string.Format("{0}{0}",hex.Substring(0, 1)), 16) / 255f;
nfloat green = Convert.ToInt32(string.Format("{0}{0}",hex.Substring(1, 1)), 16) / 255f;
nfloat blue = Convert.ToInt32(string.Format("{0}{0}",hex.Substring(2, 1)), 16) / 255f;
UIColor color = UIColor.FromRGB(red, green, blue);

you need to divide string to 3 sub strings to get red,green,blue color codes.

How to convert UIColor to SwiftUI‘s Color

Starting with beta 5, you can create a Color from a UIColor:

Color(UIColor.systemBlue)

How to Convert a string into a UIColor (Swift)

UIColor named: only works when you define a color set asset. Since your colors are defined in code, UIColor named: will never return anything but nil.

One solution is to put your colors into a dictionary instead of separate variables.

let colors: [String: UIColor] = [
"color1" : UIColor(red: 1, green: 153/255, blue: 0, alpha: 1),
"color2" : UIColor(red: 74/255, green: 134/255, blue: 232/255, alpha: 1),
"color3" : UIColor(red: 0, green: 0, blue: 1, alpha: 1),
"color4" : UIColor(red: 0, green: 1, blue: 0, alpha: 1),
"color5" : UIColor(red: 153/255, green: 0, blue: 1, alpha: 1),
"color6" : UIColor(red: 1, green: 0, blue: 0 , alpha: 1),
]

Then you can get your color as:

tile.color = colors["color\(value)"] ?? colors["color1"]!

Swift string as UIColor object

Do you want something like that ?

extension String {
func color() -> UIColor? {
switch(self){
case "red":
return UIColor.red
default:
return nil
}
}
}

Use it like that :

let rowColor = "red"
let color = rowColor.color()
print(color ?? "color not found in String extensions.")

it prints the red UIColor :
r 1,0 g 0,0 b 0,0 a 1,0

The inconvenient is that you must have all your API color identifiers declared in the String extension to convert it to the right UIColor, this solution can be improved.

How to convert UIColor to Hexadecimal (web color text string)?

I would consider using Erica Sadun's UIColor category. It includes a lot of functionality for free, including hex representations. It's pretty easy to use, just add it to whatever class header you're using it in or, add it to the pre-compiled header for ultimate flexibility.
If you're adding to the pre-compiled header, do so similar to something like this:

#ifdef __OBJC__
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "UIColor-Expanded.h"
#endif

Then You can use it like so NSLog(@"%@", [myColor hexStringFromColor]);

GitHub link to the UIColor category: https://github.com/erica/uicolor-utilities

ArsTechnica article about it: http://arstechnica.com/apple/guides/2009/02/iphone-development-accessing-uicolor-components.ars



Related Topics



Leave a reply



Submit