iOS: Create UIColor Object From A Hex String (NSString)
If you need to convert a hex value stored in an NSString into a UIColor object, you’ve come to the right place.
As an example, assume you have the value @”0A5CEA” and need a UIColor object that represents the value of the string. With the code below, creating the UIColor object is as easy as:
Notice that I also provide a parameter to set the alpha value.
The code also supports hex values in the format @”0x0A5CEA” or @”#0A5CEA” (where the later is common in web development).
Convert Hex String To Integer
The first step is to convert the hex value stored as string into an integer. I covered the specifics of this in the post Convert Hex Value Stored As NSString To Integer.
The code is duplicated here:
The code below uses the integer value of the hex string to create a UIColor object by doing a bitwise ‘&’ operation to isolate the various color attributes and divide each by 255 to get the float value:
The code below shows a few iterations:
As expected, the output for each hex string is the same:
UIColor: UIDeviceRGBColorSpace 0.0705882 0.227451 0.737255 0.9
UIColor: UIDeviceRGBColorSpace 0.0705882 0.227451 0.737255 0.9
UIColor: UIDeviceRGBColorSpace 0.0705882 0.227451 0.737255 0.9
UIColor: UIDeviceRGBColorSpace 0.0705882 0.227451 0.737255 0.9
UIColor: UIDeviceRGBColorSpace 0.0705882 0.227451 0.737255 0.9
iOS: Create UIColor Object From A Hex String (NSString)
Reviewed by Unknown
on
12:06
Rating:
No hay comentarios: