2014-07-12 50 views
0

我有一個圖層,並在其drawInContext:我畫一個屬性的字符串與drawInRect:。這是我如何初始化圖層。動畫NSMutableAttributedString顏色 - 字符串消失

+ (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屬性?

回答

0

這是一個簡單的實現- (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; 
} 

現在物業結轉,結果如預期。