简体   繁体   English

动画NSMutableAttributedString颜色-字符串消失

[英]Animating NSMutableAttributedString color - the string disappears

I have a layer and in its drawInContext: I draw an attributed string with drawInRect: . 我有一个图层,并在其drawInContext:使用drawInRect:绘制属性字符串。 Here's how I initialise the layer. 这是初始化层的方法。

+ (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;
}

I want to animate the string's color, so I have three dynamics properties. 我想动画字符串的颜色,所以我有三个动力学特性。

@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;

/* ... */

In the draw method, I set the foreground color. 在draw方法中,我设置前景色。

/* 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];

The character appears on screen as desired. 该字符将根据需要显示在屏幕上。 But once I add a CABasicAnimation to the layer, the symbol just disappears. 但是,一旦我将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"];

What does this symptom imply? 这种症状意味着什么? How do I animate NSAttributedString attributes? 我如何动画NSAttributedString属性?

This was a simple question of implementing the - (id)initWithLayer:(id)layer method, because it gets called once the animation begins. 这是实现的一个简单的问题- (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;
}

Now the properties carry over and the results are as expected. 现在属性继续存在,结果如预期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM