我具有以下部件 - ColorButton,表示單個按鈕時基本上有色矩形,PaletteView,即ColorButton對象的網格。問題順帶的UIColor預設值
的代碼看起來是這樣的:
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];
}
的問題是,這是行不通的 - 沒有什麼是面圖。但是,下面的代碼工作。
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];
}
在這種情況下我通過不自動釋放的UIColor對象,相對於[的UIColor grayColor] - 自動釋放物體。
而且下面的代碼工作:
ColorButton.m
- (id)initWithFrame:(CGRect)frame andColor:(UIColor*)aColor{
self = [super initWithFrame:frame];
if (self) {
//self.color = aColor;
self.color = [UIColor redColor];
}
return self;
}
有人能解釋這是怎麼回事,爲什麼我不能傳似[的UIColor grayColor]對象?什麼是解決我的任務的正確方法 - 將顏色值從PaletteView傳遞給ColorButton?
謝謝!
賓果!此API有效!謝謝你指點我色彩空間的東西。 – lstipakov 2011-01-14 20:02:17