I have follo开发者_开发问答wing components - ColorButton, that represents single button that is basically colored rectangle, and PaletteView, that is grid of ColorButton objects.
The code looks something like this:
ColorButton.h
@interface ColorButton : UIButton {
UIColor* color;
}
-(id) initWithFrame:(CGRect)frame andColor:(UIColor*)color;
@property (nonatomic, retain) UIColor* color;
@end
ColorButton.m
@implementation ColorButton
@synthesize color;
- (id)initWithFrame:(CGRect)frame andColor:(UIColor*)aColor{
self = [super initWithFrame:frame];
if (self) {
self.color = aColor;
}
return self;
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
const float* colors = CGColorGetComponents(color.CGColor);
CGContextSetRGBFillColor(context, colors[0], colors[1], colors[2], colors[3]);
CGContextFillRect(context, rect);
}
PaletteView.m
- (void) initPalette {
ColorButton* cb = [[ColorButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30) andColor:[UIColor grayColor]];
[self addSubview:cb];
}
The problem is that it does not work - nothing is drawing in view. However, following code works.
PaletteView.m
- (void) initPalette {
UIColor *color = [[UIColor alloc]
initWithRed: (float) (100/255.0f)
green: (float) (100/255.0f)
blue: (float) (1/255.0f)
alpha: 1.0];
ColorButton* cb = [[ColorButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30) andColor:color];
[self addSubview:cb];
}
In this case I pass not autoreleased UIColor object, in comparison to [UIColor grayColor] - autoreleased object.
Also following code works:
ColorButton.m
- (id)initWithFrame:(CGRect)frame andColor:(UIColor*)aColor{
self = [super initWithFrame:frame];
if (self) {
//self.color = aColor;
self.color = [UIColor redColor];
}
return self;
}
Can someone explain what is going on here, why I cannot pass objects like [UIColor grayColor] ? And what is correct way to solve my task - pass color values from PaletteView to ColorButton ?
Thanks!
The problem is that you're asking for the color components for the CGColor with CGColorGetComponents
. This method might return a different number of components, depending on the color space of the underlying color object. For example, [UIColor grayColor]
is probably in a grayscale color space, and so is only setting colors[0].
If you want to set the fill color for a context, you can use CGContextSetFillColorWithColor
which take the CGColorRef object directly, so you don't need to use the components at all.
精彩评论