How can I use core animation to animate the background color of an NSTextField?

ε祈祈猫儿з 提交于 2019-12-05 19:19:23

问题


I'm trying to use core animation to highlight a text field as being invalid.

[[my_field animator] setBackgroundColor [NSColor yellowColor]]

Updates the field background color, but does not animate the change. Updating properties such as the position of the field animates properly. I'm assuming this is because background color isn't included in the NSAnimatablePropertyContainer search.

I've also tried creating the animation explicitly, to no avail.

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"];

Suggestions for accomplishing this?


回答1:


Merry Christmas:

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"];

This will animate the background color of a view using a backed layer. Remember to set wants layer in the init or awake:

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



回答2:


While I never managed to figure out how to animate the background color, I was able to create the desired effect by animating a CIFalseColor filter.

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"];


来源:https://stackoverflow.com/questions/4642949/how-can-i-use-core-animation-to-animate-the-background-color-of-an-nstextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!