动画NSMutableAttributedString的颜色-字符串消失



我有一个图层,在它的drawInContext:中,我用drawInRect:绘制了一个属性字符串。下面是我初始化图层的方法。

+ (id)layer
{
    Character *layer = [[self alloc] init];
    if (layer) {
        NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"Fabada" size:72]};
        layer.symbol = [[NSMutableAttributedString alloc] initWithString:@"X" attributes:attributes];
    }
    return layer;
}

我想要动画字符串的颜色,所以我有三个动态属性。

@interface Character : CALayer
@property (nonatomic, strong) NSMutableAttributedString *symbol;
@property (nonatomic) int red;
@property (nonatomic) int green;
@property (nonatomic) int blue;
@end
@implementation Character
@dynamic red;
@dynamic green;
@dynamic blue;
/* ... */

在绘制方法中,我设置了前景色。

/* Set symbol color */
NSRange range = {0, [self.symbol length]};
UIColor *foreground = [UIColor colorWithRed:self.red    / 255.0
                                      green:self.green  / 255.0
                                       blue:self.blue   / 255.0
                                      alpha:1];
[self.symbol addAttribute:NSForegroundColorAttributeName value:foreground range:range];
CGRect symbolRect; /* The frame */
[self.symbol drawInRect:symbolRect];

字符按要求出现在屏幕上。但是一旦我添加了CABasicAnimation到图层,符号就消失了。

CABasicAnimation *animation = [CABasicAnimation animation];
animation.duration = 10.0;
animation.fillMode = kCAFillModeForwards;
animation.removedOnCompletion = NO;
animation.delegate = self;
animation.fromValue = [NSNumber numberWithInt:0];
animation.toValue   = [NSNumber numberWithInt:255];
[self.character addAnimation:animation forKey:@"blue"];

这种症状意味着什么?我如何动画NSAttributedString属性?

这是实现- (id)initWithLayer:(id)layer方法的一个简单问题,因为它在动画开始时被调用。

- (id)initWithLayer:(id)layer
{
    Character *temp = (Character *)layer;
    self = [super initWithLayer:layer];
    if (self) {
        self.symbol = temp.symbol;
        self.red    = temp.red;
        self.green  = temp.green;
        self.blue   = temp.blue;
    }
    return self;
}

现在属性延续,结果如预期的那样

最新更新