gpt4 book ai didi

objective-c - CALayer 子类中的颜色属性

转载 作者:行者123 更新时间:2023-11-29 04:49:27 25 4
gpt4 key购买 nike

这让我发疯。我正在尝试更改 CALayer 子类的自定义属性“mycolor”,这是我的代码:

#import "Circle"

@interface Circle()
@property (nonatomic, strong) UIColor * mycolor;
@property (nonatomic) float initial_angle;
@property (nonatomic) float end_angle;
@end

@implementation Circle

@synthesize mycolor;
@synthesize initial_angle, end_angle;

- (id) init {
self = [super init];
if (self) {

CGFloat red = (CGFloat)random()/(CGFloat)RAND_MAX;
CGFloat blue = (CGFloat)random()/(CGFloat)RAND_MAX;
CGFloat green = (CGFloat)random()/(CGFloat)RAND_MAX;
self.mycolor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
self.backgroundColor = [UIColor clearColor].CGColor;

}
return self;
}


-(void) changeColor {
CGFloat red = (CGFloat)random()/(CGFloat)RAND_MAX;
CGFloat blue = (CGFloat)random()/(CGFloat)RAND_MAX;
CGFloat green = (CGFloat)random()/(CGFloat)RAND_MAX;
self.mycolor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}

- (void) animate {
float final = arc4random() % 360;
float afrom = self.initial_angle;
self.initial_angle = final;
CABasicAnimation * anim = [CABasicAnimation animationWithKeyPath:@"initial_angle"];
anim.fromValue = [NSNumber numberWithFloat:afrom];
anim.toValue = [NSNumber numberWithFloat:final];
anim.duration = 5;
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[self addAnimation:anim forKey:@"initial_angle"];

final = arc4random() % 360;
afrom = self.end_angle;
self.end_angle = final;
anim = [CABasicAnimation animationWithKeyPath:@"end_angle"];
anim.fromValue = [NSNumber numberWithFloat:afrom];
anim.toValue = [NSNumber numberWithFloat:final];
anim.duration = 5;
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[self addAnimation:anim forKey:@"end_angle"];

}

- (void) drawInContext:(CGContextRef)ctx {

CGContextMoveToPoint(ctx, 50, 50);
CGContextAddArc(ctx, 50, 50, 50, initial_angle*M_PI/180, end_angle*M_PI/180, 0);
CGContextClosePath(ctx);
NSLog(@"%@", self.mycolor);

CGContextSetFillColorWithColor(ctx, self.mycolor.CGColor);
CGContextFillPath(ctx);

}

+ (BOOL)needsDisplayForKey:(NSString*)key {
if ([key isEqualToString:@"initial_angle"]||
[key isEqualToString:@"end_angle"]||
[key isEqualToString:@"mycolor"]) {
return YES;
} else {
return [super needsDisplayForKey:key];
}
}

@end

changeColor 和 animate 是公共(public)方法。每秒都会调用 Animate,并在每次用户点击圆时更改颜色。

一切正常,除了在“drawInContext”中 mycolor 始终为空。不知道为什么。

最佳答案

您是否尝试过在设置 mycolor 后立即记录它的值?

你的代码看起来不错,所以肯定发生了一些奇怪的事情。您是否有可能在某处为 mycolor 创建了自定义 setter 或 getter 方法,但没有正确实现它?

我假设您正在使用 ARC - 您是否尝试过直接设置 mycolor ivar 而不是通过 setter ? (在 ARC 中应该没问题 - 它不会泄漏或意外释放)

关于objective-c - CALayer 子类中的颜色属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9116203/

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