epetousis
epetousis

Reputation: 454

How do I animate an NSColor change?

NSAnimation won't let me animate NSColor changes. How do I do this?

Upvotes: 0

Views: 481

Answers (2)

dreamlax
dreamlax

Reputation: 95315

You can use blendedColorWithFraction:ofColor:. In your animation method (whichever method is handling the animation's current value [if you don't have one, simply make one]):

NSColor *startColor = [NSColor redColor];
NSColor *targetColor = [NSColor blueColor];

float progress = [animation currentValue];
NSColor *currentColor = [startColor blendedColorWithFraction:progress ofColor:targetColor];

Edit:

What you can do is create a subclass of NSAnimation. Your subclass just needs to override the setCurrentProgress: method to determine how far along the animation you are. You can configure the rest of the animation exactly the same way. The protocol may be overkill in this scenario but it gives your subclassed animation a dedicated way to give the NSColor back to the class instance that created the animation.

@protocol MyAnimationTarget
- (void) setColorOfSomething:(NSColor *);
@end

@interface MyAnimation : NSAnimation
@property id<MyAnimationTarget> target;
@property NSColor *color1;
@property NSColor *color2;
@end

@implementation MyAnimation
@synthesize target = _target;
@synthesize color1 = _color1;
@synthesize color2 = _color2;

- (void) setCurrentProgress:(NSAnimationProgress) d
{
    [super setCurrentProgress:d];
    NSColor *currentColor = [self.color1 blendedColorWithFraction:d ofColor:self.color2];
    [self.target setColorOfSomething:currentColor];
}

@end

In your other code:

MyAnimation *myAnim = [[MyAnimation alloc] init];
myAnim.target = self; // assuming self has a setColorOfSomething: method
myAnim.color1 = [NSColor redColor];
myAnim.color2 = [NSColor blueColor];
// set up other animation stuff
[myAnim startAnimation];

Upvotes: 5

TieDad
TieDad

Reputation: 9879

Just a suggestion. Maybe you can use fade in and fade out like the following:

begin animation
obj.alpha = 0.0;
commit animation

begin animator
obj.color = newColor;
obj.alpha = 1.0;
commit animation

Upvotes: 0

Related Questions