【问题标题】:How can I use core animation to animate the background color of an NSTextField?如何使用核心动画为 NSTextField 的背景颜色设置动画?
【发布时间】:2011-01-10 01:13:52
【问题描述】:

我正在尝试使用核心动画来突出显示无效的文本字段。

[[my_field animator] setBackgroundColor [NSColor yellowColor]]

更新字段背景颜色,但不为更改设置动画。更新属性(例如字段的位置)会正确设置动画。我假设这是因为背景颜色不包含在 NSAnimatablePropertyContainer 搜索中。

我也尝试过显式创建动画,但无济于事。

CABasicAnimation *ani;
ani = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];

ani.fromValue = CGColorCreateGenericRGB(1.0,1.0,1.0,1.0);
ani.toValue = CGColorCreateGenericRGB(1.0,0.0,0.0,1.0);
ani.repeatCount = 2;
ani.autoreverses = YES;
ani.duration = 1.0;

[[my_field layer] addAnimation:ani forKey:"backgroundColor"];

对完成这项工作的建议?

【问题讨论】:

    标签: objective-c cocoa macos core-animation


    【解决方案1】:

    圣诞快乐:

    NSView *content = [[self window] contentView];
    CALayer *layer = [content layer];
    
    CABasicAnimation *anime = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
    anime.fromValue = (id)[layer backgroundColor];
    anime.toValue = (id)CGColorCreateGenericGray(0.0f, 1.0f);
    anime.duration = 5.0f;
    anime.autoreverses = YES;
    
    [layer addAnimation:anime forKey:@"backgroundColor"];
    

    这将使用支持层为视图的背景颜色设置动画。记得在 init 或 awake 中设置想要层:

    [[[self window] contentView] setWantsLayer:YES];
    

    【讨论】:

      【解决方案2】:

      虽然我从未设法弄清楚如何为背景颜色设置动画,但我能够通过设置 CIFalseColor 过滤器的动画来创建所需的效果。

      CIFilter *filter = [CIFilter filterWithName:@"CIFalseColor"];
      [filter setDefaults];
      [filter setValue:[CIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0] forKey:@"inputColor0"];
      [filter setValue:[CIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0] forKey:@"inputColor1"];
      [filter setName:@"pulseFilter"];
      [[myField layer] setFilters:[NSArray arrayWithObject:filter]];
      
      CABasicAnimation* pulseAnimation = [CABasicAnimation animation];
      pulseAnimation.keyPath = @"filters.pulseFilter.inputColor1";
      
      pulseAnimation.fromValue = [CIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
      pulseAnimation.toValue = [CIColor colorWithRed:0.995 green:1.0 blue:0.655 alpha:1.0];
      
      pulseAnimation.duration = 0.3;
      pulseAnimation.repeatCount = 1;
      pulseAnimation.autoreverses = YES;
      
      [[myField layer] addAnimation:pulseAnimation forKey:@"pulseAnimation"];
      

      【讨论】:

      • 公共 10.11 (El Capitan) beta 似乎不支持应用自定义过滤器(具有自定义名称的过滤器)。但是,当您省略 setName-line 并将 keypath 设置为 @"filters.CIFalseColor.inputColor1"; 时,该代码有效。直接。
      • 同样从 10.9 开始你需要添加 self.layerUsesCoreImageFilter = YES;
      猜你喜欢
      • 2022-12-23
      • 1970-01-01
      • 2016-01-02
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多