tags:

views:

1700

answers:

4

I want to make my own RGB colors that are UIColors and that I could use just like UIColor blackColor or any other.

+2  A: 

Use initWithRed:green:blue:alpha: or colorWithRed:green:blue:alpha:.

For example:

// create new autoreleased UIColor object named "myColor"
UIColor *myColor = [UIColor colorWithRed:0.5f green:0.5f blue:0.5f alpha:1.0f];

// create new retained UIColor object named "myColor2"
UIColor *myColor2 = [[UIColor alloc] initWithRed:0.5f green:0.5f blue:0.5f alpha:1.0f];
gerry3
But would that allow me to say something like:UIColor *orangeColor = [UIColor alloc] initWithRed:greenLblue:alpha:];and then use it later?
Jaba
Yes, with the correct syntax. I added code examples. Make sure to properly manage the memory: if you use the class convenience constructor, then you need to retain the color object or set a retained property to it.
gerry3
+1  A: 

There are a couple of ways to create a color.

I prefer to use the RGB method. If you use the RGB values, divide them by 255 (I do not remember why, but I know you need to do it).

float rd = 225.00/255.00;
float gr = 177.00/255.00;
float bl = 140.00/255.00;
[label setTextColor:[UIColor colorWithRed:rd green:gr blue:bl alpha:1.0]];

Hope this helps.....

iPhone Guy
The red, green, blue, and alpha values that are passed to the constructor need to be between 0.0 and 1.0.
gerry3
I love your example, but I accepted his because it was more comprehensive and included more. BUT I love the fact that you did the math like that. I would have never thought of that. This is bringing me back to like 3rd grade
Jaba
I can't take credit for the math.... someone else showed me it!!! haha Good luck with your app! Thanks gerry3 for explaining why we need to divide by 255 :)
iPhone Guy
+4  A: 

You can write your own method for UIColor class using categories.

#import <UIKit/UIKit.h>
@interface UIColor(NewColor)
+(UIColor *)MyColor;
@end

#import "UIColor-NewColor.h"
@implementation UIColor(NewColor)
+(UIColor *)MyColor {
     return [UIColor colorWithRed:0.0-1.0 green:0.0-1.0 blue:0.0-1.0 alpha:1.0f];
}

By this way, you create a new color and now you can call it like

[UIColor MyColor];

You can also implement this method to obtain random color. Hope this helps.

EEE
+3  A: 

I needed to define a couple of custom colors for use in several places in an app - but the colours are specific to that app. I thought about using categories, but didn't want to have extra files to include every time. I've therefore created a couple of static methods in my App delegate.

In MyAppDelegate.h

+ (UIColor*)myColor1;

In MyAppDelegate.m

+ (UIColor*)myColor1 {  
return [UIColor colorWithRed:26.0f/255.0f green:131.0f/255.0f blue:32.0f/255.0f alpha:1.0f];  
}

I have a method per color, or you could do a single method and add a parameter.

I can then use it anywhere in the app like this:

myView.backgroundColor = [MyAppDelegate myColor1];

I hope this helps someone else.

James