gpt4 book ai didi

iphone - 传递 UIColor 预设值时出现问题

转载 作者:搜寻专家 更新时间:2023-10-30 20:23:07 25 4
gpt4 key购买 nike

我有以下组件 - ColorButton,它表示基本上是彩色矩形的单个按钮,以及 PaletteView,它是 ColorButton 对象的网格。

代码看起来像这样:

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];
}

问题是它不起作用 - View 中没有绘图。但是,以下代码有效。

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 grayColor] - 自动释放的对象相比,我传递的不是自动释放的 UIColor 对象。

以下代码也有效:

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?

谢谢!

最佳答案

问题是您使用 CGColorGetComponents 请求 CGColor 的颜色分量。此方法可能会返回不同数量的组件,具体取决于基础颜色对象的颜色空间。例如,[UIColor grayColor] 可能在灰度颜色空间中,因此仅设置颜色 [0]。

如果你想为上下文设置填充颜色,你可以使用 CGContextSetFillColorWithColor 直接获取 CGColorRef 对象,所以你根本不需要使用组件。

关于iphone - 传递 UIColor 预设值时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4695060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com