wayneh
wayneh

Reputation: 4413

How to get the background color of a label - iOS 4?

I thought this would be simple, but....

How can I get the backgroundcolor of a UILabel (preferably in RGB) ?

I can't seem to find a method or a simple way to convert a UIColor to RGB.

Thanks.

EDIT: I ended up using this code:

CGFloat r,g,b,a;
const float* colors=CGColorGetComponents(myLabel.backgroundColor.CGColor);
r=colors[0];
g=colors[1];
b=colors[2];
a=colors[3];

Upvotes: 0

Views: 1250

Answers (2)

UIAdam
UIAdam

Reputation: 5313

CGFloat r,g,b,a;
UIColor *bgColor = myLabel.backgroundColor;
[bgColor getRed:&r green:&g blue:&b alpha:&a];

or pre-iOS 5:

const CGFloat *rgba = CGColorGetComponents([bgColor CGColor]);
CGFloat r = rgba[0];
CGFloat g = rgba[1];
CGFloat b = rgba[2];
CGFloat a = rgba[3];

Upvotes: 3

Julian
Julian

Reputation: 1603

How about a category?

#import <UIKit/UIKit.h>

@interface UIColor (RGBGetters)
-(CGFloat)red;
-(CGFloat)blue;
-(CGFloat)green;
@end


#import "UIColor+RGBGetters.h"

@implementation UIColor (RGBGetters)
-(CGFloat)red
{
    CGFloat r;
    [self getRed:&r green:nil blue:nil alpha:nil];
    return r;
}

-(CGFloat)green
{
    CGFloat g;
    [self getRed:nil green:&g blue:nil alpha:nil];
    return g;
}

-(CGFloat)blue
{
    CGFloat b;
    [self getRed:nil green:nil blue:&b alpha:nil];
    return b;
}
@end

You could then use it as follows:

CGFloat red=[someLabel.backgroundColor red];

Upvotes: 1

Related Questions