iAchieved.it

Software Development Tips and Tricks

By

[UIColor colorWithRed:green:blue]

If you’ve done web development and needed to add that perfect splash of color, you’ve come to appreciate websites like Color Hex or W3Schools for grabbing an HTML code like #8A2BE2 (it’s blue violet if you were curious) or an RGB code like 138,43,226 (it’s blue violet too). Or, perhaps you’ve used DigitalColor Meter on the Mac or something equivalent for Windows. What you probably haven’t seen is a tool that displays the color code in the format that for some inexplicable reason Apple chose to use with UIColor. Per the UIColor Class Reference, if I wanted to use blue violet, I would need to code up

UIColor* blueViolet = [UIColor colorWithRed:0.541176
                                      green:0.168627
                                       blue:0.886275 alpha:1.0];

From the UIColor class reference, the first parameter (what you give to colorWithRed:) should be “The red component of the color object, specified as a value from 0.0 to 1.0.” Hmm… I’ve always seen red given as hexadecimal or decimal, but never as a “value between 0.0 to 1.0” So what ends up happening is I find the color I want (usually with the DigitalColor Meter tool), pull out a calculator, and type in the R value, divide by 255, and then repeat for G and B. And here we thought computers were supposed to make our lives easier. Or better, if someone gives me a hexadecimal code, I convert to base 10 and then divide by 255.

This is all a bit too annoying, so we present our own UIColor Picker. You know how to use this tool… it’s pretty straightforward. Find the color you want, copy and paste the code. Done. Going for that teal (#008080) look? Type it in and you’re done

UIColor* teal =[UIColor colorWithRed:0.00000
                               green:0.501961
                                blue:0.501961 alpha:1.0];

As a bonus, you can slide the opacity bar to select an alpha channel value. The possibilities are endless. Well, okay, the possibilities are finite but you get the idea.

Leave a Reply

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