Animating CALayer ShadowOffset - objective-c

I want to animate the ShadowOffset of my layer with CATransaction. But the shadow appears
without animation:
[CATransaction begin];
[CATransaction setValue:[NSNumber numberWithFloat:1.2]forKey:kCATransactionAnimationDuration];
[CATransaction setValue:[NSNumber numberWithBool:NO] forKey:kCATransactionDisableActions];
logoIndex.layer.shadowOpacity = 0.2;
[logoIndex.layer setShadowOffset:CGSizeMake(10, 30)];
[logoIndex.layer setShadowRadius:5];
[CATransaction commit];
Thank you for your help

Any particular reason why you're using CATransaction? You may have a better time if you use direct property animation and add the animation to the layer.
I know this is several months old but figured I'd add my two cents in case you ever come back to it or someone else finds it.

Related

execute animation when access to a property

this is a simple code form Brad Larson u-tunes course ;)
CABasicAnimation *move = [CABasicAnimation animationWithKeyPath:#"position"];
move.duration = 1.0f;
move.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
move.removedOnCompletion = NO;
move.fillMode = kCAFillModeForwards;
CGPoint currentPosition = l.position;
CGPoint newPosition = CGPointMake(currentPosition.x + 60.0f, currentPosition.y + 60.0f);
move.toValue = [NSValue valueWithCGPoint:newPosition];
[l addAnimation:move forKey:#"position"];
l.position = newPosition;
in the last row i change the position to reflect the final state of layer because animation does not.
But when i execute this code the animation isn't executed and layer move (in 1/4 of sec) to newposition.
someone can explain me how to animate layer's position correctly?
a second question...when i run this code...every subsequent access to property "position" will perform the same animation?
thanks.
Ditch the last line, the l.position = newPosition;. Your animation will already take care of that, and by using that property setter, you’re implicitly giving the layer Core Animation’s default .25-second action.
Also, no, subsequent changes in the position of your layer will not use your 1-second animation. The properties you’re using look pretty much identical to the default animation, though, aside from the duration; a quicker way to accomplish what you’re doing would be something like this.
CGPoint currentPosition = l.position;
CGPoint newPosition = CGPointMake(currentPosition.x + 60.0f, currentPosition.y + 60.0f);
[CATransaction begin];
[CATransaction setAnimationDuration:1.0];
l.position = newPosition;
[CATransaction commit];

Using CAMediaTimingFunction with block-based UIView animations

The View Programming Guide for iOS tells us that block-based animations are the way forward, as opposed to the now almost deprecated begin/commit style animations:
Note: If you are writing an application for iOS 4 or later, you should use the block-based methods for animating your content instead. For information on how to use those methods, see “Starting Animations Using the Block-Based Methods.”
But now I'm in a situation where I need to use custom timing functions CAMediaTimingFunction so I've resorted to using CATransactions and CABasicAnimations. These classes uses the same semantical language as the deprecated UIView animations style with methods like [CATransaction begin] and [CATransaction commit]. It just feels odd in the middle of apps where everything else is block-based.
Is there a way to combine concepts like the CAMediaTimingFunctions with block-based animations?
Update 1:
A piece of example code that I would like to 'blockify' looks like this:*
[CATransaction begin];
{
[CATransaction setValue:[NSNumber numberWithFloat:3.0f] forKey:kCATransactionAnimationDuration];
CGPoint low = CGPointMake(0.150, 0.000);
CGPoint high = CGPointMake(0.500, 0.000);
[CATransaction begin];
{
CAMediaTimingFunction* perfectIn = [CAMediaTimingFunction functionWithControlPoints:low.x :low.y :1.0 - high.x :1.0 - high.y];
[CATransaction setAnimationTimingFunction: perfectIn];
CABasicAnimation *fadeIn = [CABasicAnimation animationWithKeyPath:#"opacity"];
fadeIn.fromValue = [NSNumber numberWithFloat:0];
fadeIn.toValue = [NSNumber numberWithFloat:1.0];
[viewB.layer addAnimation:fadeIn forKey:#"animateOpacity"];
}
[CATransaction commit];
}
[CATransaction commit];
Update 2
I've made an example project for another question of mine that contains the code above. It's on github.
But now I'm in a situation where I need to use custom timing functions CAMediaTimingFunction so I've resorted to using CATransactions and CABasicAnimations. These classes uses the same semantical language as the deprecated UIView animations style with methods like [CATransaction begin] and [CATransaction commit]. It just feels odd in the middle of apps where everything else is block-based.
I think you are misreading the documentation.
Block based animations are the way to do UIView animations. Period. Full stop.
This statement DOES NOT correspond to CoreAnimation. You still have to use begin/commit for CoreAnimation. Don't make the assumption that CA begin and commit are bad, just because a higher level construct (UIView) deprecated begin/commit.
Is there a way to combine concepts like the CAMediaTimingFunctions with block-based animations?
If you need the advanced capabilities of Core Anmiation, such as custom timings, you should use CoreAnimation the way it is intended (with begin/commit, etc.)
If you are trying to animate CALayers, use Core Animation.
If you are doing high-level UIView based animations, use the UIView block-based animations.
Now I'm going to go ahead and admit this looks pretty pointless but it's the quickest thing I could think of to get you a block interface and it does stop you form accidentally leaving off the being/commit
.h
+ (void)transactionWithDuration:(NSTimeInterval)duration
animations:(void (^)(void))animations;
.m
+ (void)transactionWithDuration:(NSTimeInterval)duration
animations:(void (^)(void))animations;
{
[CATransaction begin];
[CATransaction setValue:[NSNumber numberWithFloat:duration] forKey:kCATransactionAnimationDuration];
animations();
[CATransaction commit];
}
Usage with your code (assuming you made it a category on UIView)
[UIView transactionWithDuration:3 animations:^{
CGPoint low = CGPointMake(0.150, 0.000);
CGPoint high = CGPointMake(0.500, 0.000);
CAMediaTimingFunction* perfectIn =
[CAMediaTimingFunction functionWithControlPoints:low.x
:low.y
:1.0 - high.x
:1.0 - high.y];
[CATransaction setAnimationTimingFunction: perfectIn];
CABasicAnimation *fadeIn = [CABasicAnimation animationWithKeyPath:#"opacity"];
fadeIn.fromValue = [NSNumber numberWithFloat:0];
fadeIn.toValue = [NSNumber numberWithFloat:1.0];
[viewB.layer addAnimation:fadeIn forKey:#"animateOpacity"];
}];

Animating a gaussian blur using core animation?

I'm trying to animate something where it's initially blurry then it comes into focus. I guess it works OK, but when the animation is done it's still a little blurry. Am I doing this wrong?
CABasicAnimation* blurAnimation = [CABasicAnimation animation];
CIFilter *blurFilter = [CIFilter filterWithName:#"CIGaussianBlur"];
[blurFilter setDefaults];
[blurFilter setValue:[NSNumber numberWithFloat:0.0] forKey:#"inputRadius"];
[blurFilter setName:#"blur"];
[[self layer] setFilters:[NSArray arrayWithObject:blurFilter]];
blurAnimation.keyPath = #"filters.blur.inputRadius";
blurAnimation.fromValue = [NSNumber numberWithFloat:10.0f];
blurAnimation.toValue = [NSNumber numberWithFloat:1.0];
blurAnimation.duration = 1.2;
[self.layer addAnimation:blurAnimation forKey:#"blurAnimation"];
Your problem is that the animation stops and is automatically removed, but the filter lingers with the tiniest of blur applied.
What you want to do is to remove the blur filter when the animation completes. You need to add a delegate to the CABasicAnimation instance and implement the -[id<CAAnimationDelegate> animationDidStop:finished:] method.
If you let self be the delegate in this case it should be fairly simple, add this line before adding the animation to your layer:
blurAnimation.delegate = self;
And the callback is equally simple:
- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag {
[[self layer] setFilters:nil];
}
If you're looking for an optimized way to animate a blur then I recommend creating a single blurred image of your view and then fading the blurred image from alpha 0 to 1 over the top of your original view. Seems nice and fast in tests.

Animating Views with Core Animation Layer

I have a NSWindow containing a NSView with 'Wants Core Animation Layer' enabled. The view then contains many NSImageView that use are initially animated into position. When I run the animation, it is extremely sluggish and drops most of the frames. However, if I disable 'Wants Core Animation Layer' the animation works perfectly. I'm going to need the core animation layer but can't figure out how to get it to perform adequately.
Can I do anything to fix the performance issues?
Here is the code:
// AppDelegate
NSRect origin = ...;
NSTimeInterval d = 0.0;
for (id view in views)
{
[view performSelector:#selector(animateFrom:) withObject:origin afterDelay:d];
d += 0.05f;
}
// NSImageView+Animations
- (void)animateFrom:(NSRect)origin
{
NSRect original = self.frame;
[self setFrame:origin];
[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:0.20f];
[[self animator] setFrame:original];
[NSAnimationContext endGrouping];
}
It's possible that the NSTimer is killing your performance. Core Animation has rich support for controlling the timing of animations through the CAMediaTiming protocol, and you should take advantage of that in your app. Instead of using the animator proxy and NSAnimationContext, try using Core Animation directly. If you create a CABasicAnimation for each image and set its beginTime, it will delay the start of the animation. Also, for the delay to work the way you want, you must wrap each animation in a CAAnimationGroup with its duration set to the total time of the entire animation.
Using the frame property could also be contributing to the slowdown. I really like to take advantage of the transform property on CALayer in situations like this where you're doing an "opening" animation. You can lay out your images in IB (or in code) at their final positions, and right before the window becomes visible, modify their transforms to the animation's starting position. Then, you just reset all of the transforms to CATransform3DIdentity to get the interface into its normal state.
I have an example in my <plug type="shameless"> upcoming Core Animation book </plug> that's very similar to what you're trying to do. It animates 30 NSImageViews simultaneously with no dropped frames. I modified the example for you and put it up on github. These are the most relevant bits of code with the extraneous UI stuff stripped out:
Transform the layers to their start position
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// ... SNIP ... //
//Start with all of the images at the origin
[CATransaction begin];
[CATransaction setDisableActions:YES];
for (CALayer *imageLayer in [[[self imageContainer] layer] sublayers]) {
CGPoint layerPosition = [layer position];
CATransform3D originTransform = CATransform3DMakeTranslation(20.f - layerPosition.x, -layerPosition.y, 0.f);
[imageLayer setTransform:originTransform];
}
[CATransaction commit];
}
Animate the transform back to the identity
- (IBAction)runAnimation:(id)sender {
CALayer *containerLayer = [[self imageContainer] layer];
NSTimeInterval delay = 0.f;
NSTimeInterval delayStep = .05f;
NSTimeInterval singleDuration = [[self durationStepper] doubleValue];
NSTimeInterval fullDuration = singleDuration + (delayStep * [[containerLayer sublayers] count]);
for (CALayer *imageLayer in [containerLayer sublayers]) {
CATransform3D currentTransform = [[imageLayer presentationLayer] transform];
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:#"transform"];
anim.beginTime = delay;
anim.fromValue = [NSValue valueWithCATransform3D:currentTransform];
anim.toValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
anim.fillMode = kCAFillModeBackwards;
anim.duration = singleDuration;
CAAnimationGroup *group = [CAAnimationGroup animation];
group.animations = [NSArray arrayWithObject:anim];
group.duration = fullDuration;
[imageLayer setTransform:CATransform3DIdentity];
[imageLayer addAnimation:group forKey:#"transform"];
delay += delayStep;
}
}
I also have a video on YouTube of the example in action if you want to check it out.
Did you try to batch everything in a CATransaction?
[CATransaction begin];
for {...}
[CATransaction commit];
CATransaction is the Core Animation mechanism for batching multiple layer-tree operations into atomic updates to the render tree.

Add a sublayer to a CALayer without animation?

How can I add a sublayer to a CALayer without animation? Usually when you add one it "fades in" and when you remove one it "fades out".
How to supress the animation?
Have you tried this:
[CATransaction begin];
[CATransaction setValue:(id)kCFBooleanTrue
forKey:kCATransactionDisableActions];
[layer addSublayer:sublayer];
[CATransaction commit];
from the Apple docs?
You can also suppress implicit layer addition animations by setting the actions dictionary on the superlayer, like I describe in this answer:
NSMutableDictionary *newActions = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[NSNull null], #"sublayers", nil];
superlayer.actions = newActions;
[newActions release];
You can use
[CATransaction setAnimationDuration:0.0f];