multiple CAKeyframeAnimation in different layers at the same time - iphone

Does anyone now how can I animate multiple layers at the same time using CAKeyframeAnimation ?
Each layer has its own CAKeyframeAnimation object. Take a look at the code below:
I have a method that receives an object, creates the CAKeyframeAnimation and attaches the animation to it:
- (void)animateMovingObject:(CALayer*)obj
fromPosition:(CGPoint)startPosition
toPosition:(CGPoint)endPosition
duration:(NSTimeInterval)duration {
CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:#"position"];
pathAnimation.calculationMode = kCAAnimationPaced;
//pathAnimation.fillMode = kkCAFillModeRemoved; // default
//pathAnimation.removedOnCompletion = YES; // default
pathAnimation.duration = duration;
// create an empty mutable path
CGMutablePathRef curvedPath = CGPathCreateMutable();
// set the starting point of the path
CGPathMoveToPoint(curvedPath, NULL, startPosition.x, startPosition.y);
CGPathAddCurveToPoint(curvedPath, NULL,
startPosition.x, endPosition.y,
startPosition.x, endPosition.y,
endPosition.x, endPosition.y);
pathAnimation.path = curvedPath;
[obj addAnimation:pathAnimation forKey:#"pathAnimation"];
CGPathRelease(curvedPath);
}
Now, suppose I have 3 layers added as a sublayer in my board game and I make the following calls:
CALayer obj1 = ... // set up layer and add as sublayer
[self animateMovingObject:obj1
fromPosition:CGPointMake(0.0, 0.0)
toPosition:CGPointMake(100.0, 100.0)
duration:2.0];
CALayer obj2 = ... // set up layer and add as sublayer
[self animateMovingObject:obj2
fromPosition:CGPointMake(0.0, 0.0)
toPosition:CGPointMake(150.0, 100.0)
duration:2.0];
CALayer obj3 = ... // set up layer and add as sublayer
[self animateMovingObject:obj3
fromPosition:CGPointMake(0.0, 0.0)
toPosition:CGPointMake(200.0, 100.0)
duration:2.0];
By doing this, I can see only the obj3 being moved from position (0.0, 0.0) to (200.0, 100.0).
What am I missing? Should I use NSOperationQueue/Threads?
Using the animationDidStart: delegate method of the CAKeyframeAnimation doesn't seem to be useful in this context.
Any ideas?
Thanks in advance.

If you want to group a series of animations like this, so that they are guaranteed to be synchronized, you could wrap them in a CATransaction:
[CATransaction begin];
[CATransaction setValue:[NSNumber numberWithFloat:2.0] forKey:kCATransactionAnimationDuration];
// Do animations
[CATransaction commit];
However, I'm not quite sure why the code you've written doesn't fire off the correct animations for each layer, even if they weren't synchronized.
Note that by setting removedOnCompletion to YES, your animation will run and then the object will hop back to its starting point at the end. You probably want that to be NO.

Related

How do I animate CATransform3Ds with a CAKeyframeAnimation?

I've used CAKeyframeAnimations to animate a layer's transform.rotation and transform.translation.x properties, but I'm having trouble animating the transform property implicitly. I have a layer that must animate between two states and CABasicAnimation's default interpolation is totally incorrect and doesn't follow the path I want. CAKeyframeAnimation to the rescue, or so I thought. Any attempt to animate transform using a CAKeyframeAnimation results in the view immediately snapping to the final transform while the other animations run. If I remove the first half of the following function and let my "transform" events use the CABasicAnimation on the bottom, it animates just fine - albeit with incorrectly interpolated transforms along the way.
My layer delegate has implemented the following:
- (id <CAAction>) actionForLayer:(CALayer *)layer forKey:(NSString *)event
{
if ([event isEqualToString:#"transform"])
{
CGSize startSize = ((CALayer *)self.layer.presentationLayer).bounds.size;
CGSize endSize = self.layer.bounds.size;
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:event];
animation.duration = 0.25;
NSMutableArray *values = [NSMutableArray array];
int stepCount = 10;
for (int i = 0; i < stepCount; i++)
{
CGFloat p = i / (float)(stepCount - 1);
CGSize size = [self interpolateBetweenSize:startSize andSize:endSize percentage:p];
CATransform3D transform = [self transformForSize:size];
[values addObject:[NSValue valueWithCATransform3D:transform]];
}
animation.values = values;
return animation;
}
// All other animations use this basic animation
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:event];
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animation.removedOnCompletion = YES;
animation.fillMode = kCAFillModeForwards;
animation.duration = 0.25;
return animation;
}
My transform is a translation followed by a rotate, but I think a group animation with separate keyframe animations animating through a translation AND a rotate would result in crazy town. I've confirmed that size & transform are correct for all values of p that I pass though, and p strictly ranges from 0 to 1.
I've tried setting a non-default timing function, I've tried setting an array of timing functions, I've omitted the keyTImes, I've set a repeatCount of 0, removedOnCompletion=YES, and a fillMode of forwards and that had no effect. Am I not creating the transform keyframe animation correctly?
This technique worked back in iOS 3 but seemed to be broken in iOS 5.0.
5.1 'magically' fixed this, it seemed to be a bug in iOS 5.0. I'd file a radar, but it is now working in 5.1.
#Gsnyder: Some background: I am experimenting with Clear-like UI (for something completely unrelated to Clear) and came up with this: http://blog.massivehealth.com/post/18563684407/clear. That should explain the need for a rotate & translate.
I've since created a shutter transition that subdivides a view into N layers (instead of just 2) that looks like this when viewed from the side: /////.
My code is not animating the bounds, it is using the size at each step to determine the necessary transform.
#Paul.s: Implicit allows me to keep this abstraction within the layer class itself without polluting the view controller that owns it. The view controller should just be changing the bounds around and the layer should move appropriately. I'm not a fan of view controllers having dozens of custom animations when the views themselves can handle it.
I need to use a keyframe animation because the default animation between layer transforms / and _ animate through incorrect angles so the ///\ layers do not line up throughout the transform. The keyframe animations ensure the edges all line up correctly while they all animate.
I'm considering this closed, this seems to be a bug in iOS 5.0 and has since been fixed. Thanks everyone.
(void)animateViewWith3DCurrentView:(UIView *)currentView withPoing:(CGPoint)movePoint
{
//flip the view by 180 degrees in its place first.
currentView.layer.transform = CATransform3DRotate(currentView.layer.transform,myRotationAngle(180), 0, 1, 0);
//set the anchor point so that the view rotates on one of its sides.
currentView.layer.anchorPoint = CGPointMake(0.5, 0.5);
//Set up scaling
CABasicAnimation *resizeAnimation = [CABasicAnimation animationWithKeyPath:kResizeKey];
//we are going to fill the screen here. So 423,337
[resizeAnimation setToValue:[NSValue valueWithCGSize:CGSizeMake(423, 337)]];
resizeAnimation.fillMode = kCAFillModeForwards;
resizeAnimation.removedOnCompletion = NO;
// Set up path movement
UIBezierPath *movePath = [UIBezierPath bezierPath];
//the control point is now set to centre of the filled screen. Change this to make the path different.
// CGPoint ctlPoint = CGPointMake(0.0, 0.5);
CGPoint ctlPoint = CGPointMake(1024/2, 768/2);
//This is the starting point of the animation. This should ideally be a function of the frame of the view to be animated. Hardcoded here.
// Set here to get the accurate point..
[movePath moveToPoint:movePoint];
//The anchor point is going to end up here at the end of the animation.
[movePath addQuadCurveToPoint:CGPointMake(1024/2, 768/2) controlPoint:ctlPoint];
CAKeyframeAnimation *moveAnim = [CAKeyframeAnimation animationWithKeyPath:kPathMovement];
moveAnim.path = movePath.CGPath;
moveAnim.removedOnCompletion = YES;
// Setup rotation animation
CABasicAnimation* rotateAnimation = [CABasicAnimation animationWithKeyPath:kRotation];
//start from 180 degrees (done in 1st line)
CATransform3D fromTransform = CATransform3DMakeRotation(myRotationAngle(180), 0, 1, 0);
//come back to 0 degrees
CATransform3D toTransform = CATransform3DMakeRotation(myRotationAngle(0), 0, 1, 0);
//This is done to get some perspective.
CATransform3D persp1 = CATransform3DIdentity;
persp1.m34 = 1.0 / -3000;
fromTransform = CATransform3DConcat(fromTransform, persp1);
toTransform = CATransform3DConcat(toTransform,persp1);
rotateAnimation.toValue = [NSValue valueWithCATransform3D:toTransform];
rotateAnimation.fromValue = [NSValue valueWithCATransform3D:fromTransform];
//rotateAnimation.duration = 2;
rotateAnimation.fillMode = kCAFillModeForwards;
rotateAnimation.removedOnCompletion = NO;
// Setup and add all animations to the group
CAAnimationGroup *group = [CAAnimationGroup animation];
[group setAnimations:[NSArray arrayWithObjects:moveAnim,rotateAnimation, resizeAnimation, nil]];
group.fillMode = kCAFillModeForwards;
group.removedOnCompletion = NO;
group.duration = 0.7f;
group.delegate = self;
[group setValue:currentView forKey:kGroupAnimation];
[currentView.layer addAnimation:group forKey:kLayerAnimation];
}

The scope of a CATransaction block

I have seen some code that removes a given layer from it's superlayer by doing the following:
void RemoveImmediately(CALayer *layer) {
[CATransaction flush];
[CATransaction begin];
[CATransaction setValue:(id)kCFBooleanTrue
forKey:kCATransactionDisableActions];
[layer removeFromSuperlayer];
[CATransaction commit];
}
I have written a method that changes the position of a given layer in an animated way using CAKeyframeAnimation, which looks like this:
- (void)animateMovingObject:(NXUIObject*)obj
fromPosition:(CGPoint)startPosition
toPosition:(CGPoint)endPosition
duration:(NSTimeInterval)duration {
CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:#"position"];
pathAnimation.calculationMode = kCAAnimationPaced;
pathAnimation.duration = duration;
CGMutablePathRef curvedPath = CGPathCreateMutable();
CGPathMoveToPoint(curvedPath, NULL, startPosition.x, startPosition.y);
CGPathAddCurveToPoint(curvedPath, NULL,
startPosition.x, endPosition.y,
startPosition.x, endPosition.y,
endPosition.x, endPosition.y);
pathAnimation.path = curvedPath;
[obj addAnimation:pathAnimation forKey:#"pathAnimation"];
CGPathRelease(curvedPath);
}
Up to know, everything is fine. Now suppose I have in my app a 'master layer', which has 3 sublayers. I want the first two sublayers to be moved to another position and the last one to be removed. So I did the following:
CALayer obj1 = ... // set up layer and add as sublayer
[self.masterLayer addSublayer:obj1];
[self animateMovingObject:obj1
fromPosition:CGPointMake(0.0, 0.0)
toPosition:CGPointMake(100.0, 100.0)
duration:2.0];
CALayer obj2 = ... // set up layer and add as sublayer
[self.masterLayer addSublayer:obj2];
[self animateMovingObject:obj2
fromPosition:CGPointMake(0.0, 0.0)
toPosition:CGPointMake(150.0, 100.0)
duration:2.0];
CALayer obj3 = ... // set up layer and add as sublayer
[self.masterLayer addSublayer:obj3];
// ...
RemoveImmediately(obj3); // This removes the two previous animations too
//[obj3 removeFromSuperlayer]; // This just removes obj3, the previous animations works
Note that if I call RemoveImmediately(), even passing obj3 as argument I can't see the first two layers being animated. However, if I remove the obj3 just by calling removeFromSuperlayer the first two layers are animated normally.
Looks like the CATransaction block cancels all animations being done, even those that were created with CAKeyframeAnimation.
What I'm I missing?
Thanks In advance.
The scope of a CATransaction should just be between the [CATransaction begin] and [CATransaction commit] lines.
Also, you shouldn't need the [CATransaction flush] in that code. Apple generally recommends you not force the execution of pending transactions for performance reasons, and the transaction you're setting up there should not affect any pending animations.
I'm guessing this odd behavior is still related to what you asked in your previous question, where the three animations are somehow interfering with one another. As I commented there, this is behaving like the three animations are being added to one layer, not three independent ones. I'd check and make sure there was no possibility of that happening (crossed pointers, etc.).

CABasicAnimation not animating my property

I've been trying to understand what is wrong with my animation and I still haven't figure it out. I think it should be really straight forward, but there is probably something I'm missing, even after reading lot of examples and documentation.
My problem comes originally form the fact that on the iPhone, you cannot resize layers automatically (with the view). The documentation says otherwise but there is no autoresizeMask for the layer in the SDKs. So I decided to make a little workaround and animate the layer myself.
I've got this simple piece of code that should do a simple resize animation. The values are good and I even set the delegate in order to trace if the anim start/end.
// I've got a property named layerImage (which is a CALayer)
- (void)animateTestWithFrame:(CGRect)value {
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"layerImage.frame"];
animation.duration = 1;
animation.fromValue = [NSValue valueWithCGRect:self.frame];
animation.toValue = [NSValue valueWithCGRect:value];
animation.removedOnCompletion = YES;
animation.delegate = self;
[self.layer addAnimation:animation forKey:#"layerImage.frame"];
}
So, any ideas? (This view that contains the code is the subview of a subview of the window if that could make a difference)
--- EDIT ---
It seems that frame is not animatable via CABasicAnimation and the named property "frame". When using bounds, I've got some strange result, but at least I'm getting something. Will continue investigating on this.
So it's good that you've figured things out here, but your answer to your own question has some inaccuracies. Let me correct a few things:
The frame property can be animated--just not with explicit animation. If you do the following to a layer other than the root layer of a view, the frame will animate just fine:
[CATransaction begin];
[CATransaction setAnimationDuration:2.0f];
[animationLayer setFrame:CGRectMake(100.0f, 100.0f, 100.0f, 100.0f)];
[CATransaction commit];
Remember that setting a property on a layer will animate that property change by default. In fact you have to disable animations on a property change if you don't want it to animate. (Of course this is only true if you are animating a layer other than the root layer of a view.) You are correct in animating both position and bounds if you need to use an explicit animation.
You can animate the frame on a UIView using implicit animation:
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:3.0f];
[[self view] setFrame:CGRectMake(45.0f, 45.0f, 100.0f, 100.0f)];
[UIView commitAnimations];
This will animate from the view's current frame (bounds and position) to x = 45.0, y = 45.0, w = 100.0, h = 100.0.
It seems you may also be misunderstanding the difference between an animation and a layer. You add animations to layers, but adding an animation to a layer does not automatically set the property that you're animating.
CALayers are model objects. They contain information about the layer that eventually gets rendered to screen. You must set a layer's property if you want that property to actually have that value. If you simply animate the property, it will only be a visual representation and not actual--which is to say this is why the value snaps back to the original value of the layer because you never actually changed it.
Which leads me to the next point. You said:
Use "animation.removedOnCompletion =
NO; animation.fillMode =
kCAFillModeForwards;" to ensure that
the values are not reseted at the end
of the animation
This is not exactly right. These two values simply cause the animation to remain at it's final position visually, however, the layer's actual values have not changed. They are still the exact same values they were when you started the animation. In general (with a few exceptions) you don't want to use these two parameters because they are visual only. What you want is to actually set the layer value for the property you're animating.
Say, for example, that you want to animate the position of your layer using an explicit animation. Here is the code you want:
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"position"];
[animation setFromValue:[NSValue valueWithCGPoint:CGPointMake(70.0f, 70.0f)]];
[animation setToValue:[NSValue valueWithCGPoint:CGPointMake(150.0f, 150.0f)]];
[animation setDuration:2.0f];
// Actually set the position on the *layer* that you want it to be
// when the animation finishes.
[animationLayer setPosition:CGPointMake(150.0f, 150.0f)];
// Add the animation for the position key to ensure that you
// override the animation for position changes with your animation.
[animationLayer addAnimation:animation forKey:#"position"];
You may also want to consider animation grouping. With an animation group, you can group several animations together and then control how they relate to each other. In your case the duration for your bounds and position animations are the same and so what you are trying to do will work fine without a group, but if you wanted to offset the start of the animations, for example you didn't want the position animation to start until a second or two into the frame animation, you could stagger them by setting the beginTime value of the position animation.
Finally, I would be curious to know why you couldn't use the implicit animations available on UIView. I use these in the vast majority of the Core Animation code I write and can't see why this wouldn't work for your situation.
Best regards.
The key path should only be the key path of the property, not the name of the object as well.
Use this
[CABasicAnimation animationWithKeyPath:#"frame"]
instead of this
[CABasicAnimation animationWithKeyPath:#"layerImage.frame"]
And just BTW, when you add animation to a layer, the key doen't mean the key property to animate. Just the key (name) that you want this animation to have (this refers to the last line your code)
So, the solution was to animate the #"bounds" and the #"position" of the layer because frame is not animatable on iPhone. It took me some time to understand that the position was the center of the layer and the resize of the bounds was extending from the center, but that was the easy part.
So, what I did in resume was:
In the setFrame, create 2 animations with the bounds and position property.
Use "animation.removedOnCompletion = NO; animation.fillMode = kCAFillModeForwards;" to ensure that the values are not reseted at the end of the animation
Register the delegate to self in order to implements "animationDidStop:finished:". It seems that you still need to set the values: "layerImage.bounds = [animation.toValue CGRectValue]; layerImage.position = [animation.toValue CGPointValue];".
I wasn't able to use the UIView animation system directly because it wasn't doing what I wanted on the layers.
Thanks tadej5553 for pointing me out the layer problem I had with the "addAnimation". So here is the code for those who would like to see what it looks like.
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
CABasicAnimation *animation = (CABasicAnimation*)anim;
if ([animation.keyPath isEqualToString:#"bounds"]) {
layerImage.bounds = [animation.toValue CGRectValue];
} else if ([animation.keyPath isEqualToString:#"position"]) {
layerImage.position = [animation.toValue CGPointValue];
}
}
- (void)setFrame:(CGRect)value {
CGRect bounds = CGRectMake(0, 0, value.size.width, value.size.height);
if ([UIView isAnimationStarted]) {
// animate the bounds
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"bounds"];
animation.duration = [UIView animationDuration];
animation.fromValue = [NSValue valueWithCGRect:layerImage.bounds];
animation.toValue = [NSValue valueWithCGRect:bounds];
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
animation.timingFunction = [UIView animationFunction];
animation.delegate = self;
[layerImage addAnimation:animation forKey:#"BoundsAnimation"];
// animate the position so it stays at 0, 0 of the frame.
animation = [CABasicAnimation animationWithKeyPath:#"position"];
animation.duration = [UIView animationDuration];
animation.fromValue = [NSValue valueWithCGPoint:layerImage.position];
animation.toValue = [NSValue valueWithCGPoint:CGPointMake(bounds.size.width / 2, bounds.size.height / 2)];
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
animation.timingFunction = [UIView animationFunction];
animation.delegate = self;
[layerImage addAnimation:animation forKey:#"PositionAnimation"];
} else {
layerImage.frame = bounds;
}
[super setFrame:value];
}

CATransaction: Layer Changes But Does Not Animate

I'm trying to animate part of UI in an iPad app when the user taps a button. I have this code in my action method. It works in the sense that the UI changes how I expect but it does not animate the changes. It simply immediately changes. I must be missing something:
- (IBAction)someAction:(id)sender {
UIViewController *aViewController = <# Get an existing UIViewController #>;
UIView *viewToAnimate = aViewController.view;
CALayer *layerToAnimate = viewToAnimate.layer;
[CATransaction begin];
[CATransaction setAnimationDuration:1.0f];
CATransform3D rotateTransform = CATransform3DMakeRotation(0.3, 0, 0, 1);
CATransform3D scaleTransform = CATransform3DMakeScale(0.10, 0.10, 0.10);
CATransform3D positionTransform = CATransform3DMakeTranslation(24, 423, 0);
CATransform3D combinedTransform = CATransform3DConcat(rotateTransform, scaleTransform);
combinedTransform = CATransform3DConcat(combinedTransform, positionTransform);
layerToAnimate.transform = combinedTransform;
[CATransaction commit];
// rest of method...
}
I've tried simplifying the animation to just change the opacity (for example) and it still will not animate. The opacity just changes instantly. That leads me to believe something is not setup properly.
Any clues would be helpful!
Animations on the root layer of a view are disabled by default. Try applying a transform to the view instead, e.g. [view setTransform:CGTransform3D...]. If you must do it at the layer level, add a layer to the root layer and perform your transforms on it instead. Also the view animation block [UIView beginAnimations...] only has an effect when animating view properties--as opposed to layer properties.
Update:
So here is what your code would look like with explicit animation (CATransaction is not required)
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:#"transform"];
CATransform3D rotateTransform = CATransform3DMakeRotation(0.3, 0, 0, 1);
CATransform3D scaleTransform = CATransform3DMakeScale(0.10, 0.10, 0.10);
CATransform3D positionTransform = CATransform3DMakeTranslation(24, 423, 0);
CATransform3D combinedTransform = CATransform3DConcat(rotateTransform, scaleTransform);
combinedTransform = CATransform3DConcat(combinedTransform, positionTransform);
[anim setFromValue:[NSValue valueWithCATransform3D:CATransform3DIdentity]];
[anim setToValue:[NSValue valueWithCATransform3D:combinedTransform]];
[anim setDuration:1.0f];
[layerToAnimate addAnimation:anim forKey:nil];
Keep in mind that this only performs the animation. You actually have to set the transform property of the layer with a call to:
[layerToAnimate setTransform:combinedTransform];
as well. Otherwise it will just snap back to its starting position.
Layer properties are animated implicitly whenever you set them except in the case where you are animating the root layer of a view. In that case animations are turned off by default and I've found that what I always have to do instead is animate the view rather than the layer when I am interested in animating the root. So what this means is that a call to any layer within your layer tree that makes a property change will be animated implicitly. For example:
CALayer *root = [view layer];
CALayer *sublayer = [[root sublayers] objectAtIndex:0];
[sublayer setTransform:combinedTransform];
This is the only way I know (knew) you can actually use implicit animation on a layer. However, what your code has pointed out is that you can turn the layer animation on for the root layer simply by placing the changes to the layer within a UIView animation block. That's pretty interesting and handy. This is quite a helpful discovery.
Maybe this is buried in the docs somewhere, but I have yet to come across it.
Setting your layerToAnimate delegate to your rootView.layer works:
viewToAnimate.layer.delegate = rootView.layer;
Assuming you add the view/layer to the root view/layer as well. Cannot find where this changed, implicit animations use to just work.
It turns out you can turn the layer animation on for the root layer by setting its delegate property to nil. I don't know if it's good practice.

Animating a CALayer's mask size change

I have a UIView subclass which uses a CAShapeLayer mask on its CALayer. The mask uses a distinct shape, with three rounded corners and a cut out rectangle in the remaining corner.
When I resize my UIView using a standard animation block, the UIView itself and its CALayer resize just fine. The mask, however, is applied instantly, which leads to some drawing issues.
I've tried animating the mask's resizing using a CABasicAnimation but didn't have any luck getting the resizing animated.
Can I somehow achieve an animated resizing effect on the mask? Do I need to get rid of the mask, or will I have to change something about the way I currently draw the mask (using - (void)drawInContext:(CGContextRef)ctx).
Cheers,
Alex
I found the solution to this problem. Other answers are partially correct and are helpful.
The following points are important to understanding the solution:
The mask property is not animatable itself.
Since the mask is a CALayer it can be animated on its own.
Frame is not animatable, use bounds and position. This may not apply to you(if you weren't trying to animate the frame), but was an issue for me. (See Apple QA 1620)
A view layer's mask is not tied to UIView so it will not receive the core animation transaction that is applied to the view's layer.
We are modifying the CALayer directly, so we can't expect that UIView will have any idea of what we are trying to do, so the UIView animation won't create the core animation transaction to include changes to our properties.
In order to solve, we are going to have to tap into Core Animation ourselves, and can't rely on the UIView animation block to do the work for us.
Simply create a CATransaction with the same duration that you are using with [UIView animateWithDuration:...]. This will create a separate animation, but if your durations and easing function is the same, it should animate exactly with the other animations in your animation block.
NSTimeInterval duration = 0.5;// match this to the value of the UIView animateWithDuration: call
[CATransaction begin];
[CATransaction setValue:[NSNumber numberWithFloat:duration] forKey:kCATransactionAnimationDuration];
self.myView.layer.mask.position = CGPointMake(newX, 0);
self.myView.layer.mask.bounds = CGRectMake(0, 0, newWidth, newHeight);
[CATransaction commit];
I use a CAShapeLayer to mask a UIView by setting self.layer.mask to that shape layer.
To animate the mask whenever the size of the view changes I overwrote the -setBounds: to animate the mask layer path if the bounds are changed during an animation.
Here's how I implemented it:
- (void)setBounds:(CGRect)bounds
{
[super setBounds:bounds];
CAPropertyAnimation *boundsAnimation = (CABasicAnimation *)[self.layer animationForKey:#"bounds"];
// update the mask
self.maskLayer.frame = self.layer.bounds;
// if the bounds change happens within an animation, also animate the mask path
if (!boundsAnimation) {
self.maskLayer.path = [self createMaskPath];
} else {
// copying the original animation allows us to keep all animation settings
CABasicAnimation *animation = [boundsAnimation copy];
animation.keyPath = #"path";
CGPathRef newPath = [self createMaskPath];
animation.fromValue = (id)self.maskLayer.path;
animation.toValue = (__bridge id)newPath;
self.maskLayer.path = newPath;
[self.maskLayer addAnimation:animation forKey:#"path"];
}
}
(For the example self.maskLayer is set to `self.layer.mask)
My -createMaskPath calculates the CGPathRef that I use to mask the view. I also update the mask path in -layoutSubviews.
The mask property of CALayer is not animatable which explains your lack of luck in that direction.
Does the drawing of your mask depend on the frame/bounds of the mask? (Can you provide some code?) Does the mask have needsDisplayOnBoundsChange property set?
Cheers,
Corin
To animate the bounds change of the mask layer of a UIView: subclass UIView, and animate the mask with a CATransaction - similar to Kekodas answer but more general:
#implementation UIMaskView
- (void) layoutSubviews {
[super layoutSubviews];
CAAnimation* animation = [self.layer animationForKey:#"bounds"];
if (animation) {
[CATransaction begin];
[CATransaction setAnimationDuration:animation.duration];
}
self.layer.mask.bounds = self.layer.bounds;
if (animation) {
[CATransaction commit];
}
}
#end
The mask parameter doesn't animate, but you can animate the layer which is set as the mask...
If you animate the CAShapeLayer's Path property, that should animate the mask. I can verify that this works from my own projects. Not sure about using a non-vector mask though. Have you tried animating the contents property of the mask?
Thanks,
Jon
I couldn't find any programmatical solution so I just draw an png image with correct shape and alpha values and used that instead. That way I don't need to use a mask...
It is possible to animate the mask change.
I prefer to use CAShapeLayer as the mask layer. It is very convenient to animate a mask change with the help of property path.
Before animate any change, dump the content of the source into an instance CGImageRef, and create a new layer for animation. Hide the original layer during the animation and show it when animation ends.
The following is a sample code for creating key animation on property path.
If you want to create your own path animation, make sure that there are always same number of points in the paths.
- (CALayer*)_mosaicMergeLayer:(CGRect)bounds content:(CGImageRef)content isUp:(BOOL)isUp {
CALayer* layer = [CALayer layer];
layer.frame = bounds;
layer.backgroundColor = [[UIColor clearColor] CGColor];
layer.contents = (id)content;
CAShapeLayer* maskLayer = [CAShapeLayer layer];
maskLayer.fillColor = [[UIColor blackColor] CGColor];
maskLayer.frame = bounds;
maskLayer.fillRule = kCAFillRuleEvenOdd;
maskLayer.path = ( isUp ? [self _maskArrowUp:-bounds.size.height*2] : [self _maskArrowDown:bounds.size.height*2] );
layer.mask = maskLayer;
CAKeyframeAnimation* ani = [CAKeyframeAnimation animationWithKeyPath:#"path"];
ani.removedOnCompletion = YES;
ani.duration = 0.3f;
ani.fillMode = kCAFillModeForwards;
ani.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
NSArray* values = ( isUp ?
[NSArray arrayWithObjects:
(id)[self _maskArrowUp:0],
(id)[self _maskArrowUp:-ceilf(bounds.size.height*1.2)],
nil]
:
[NSArray arrayWithObjects:
(id)[self _maskArrowDown:0],
(id)[self _maskArrowDown:bounds.size.height],
nil]
);
ani.values = values;
ani.delegate = self;
[maskLayer addAnimation:ani forKey:nil];
return layer;
}
- (void)_startMosaicMergeAni:(BOOL)up {
CALayer* overlayer = self.aniLayer;
CGRect bounds = overlayer.bounds;
self.firstHalfAni = NO;
CALayer* frontLayer = nil;
frontLayer = [self _mosaicMergeLayer:bounds
content:self.toViewSnapshot
isUp:up];
overlayer.contents = (id)self.fromViewSnapshot;
[overlayer addSublayer:frontLayer];
}
Swift 3+ answer based on Kekoa's solution:
let duration = 0.15 //match this to the value of the UIView.animate(withDuration:) call
CATransaction.begin()
CATransaction.setValue(duration, forKey: kCATransactionAnimationDuration)
myView.layer.mask.position = CGPoint(x: [new X], y: [new Y]) //just an example
CATransaction.commit()
Swift implementation of #stigi answer, my mask layer is called shape Layer
override var bounds: CGRect {
didSet {
// debugPrint(self.layer.animationKeys()) //Very useful for know if animation is happening and key name
let propertyAnimation = self.layer.animation(forKey: "bounds.size")
self.shapeLayer?.frame = self.layer.bounds
// if the bounds change happens within an animation, also animate the mask path
if let boundAnimation = propertyAnimation as? CABasicAnimation {
// copying the original animation allows us to keep all animation settings
if let basicAnimation = boundAnimation.copy() as? CABasicAnimation {
basicAnimation.keyPath = "path"
let newPath = UIBezierPathUtils.customShapePath(rect: self.layer.bounds, cornersTriangleSize: cornerTriangleSize).cgPath
basicAnimation.fromValue = self.shapeLayer?.path
basicAnimation.toValue = newPath
self.shapeLayer?.path = newPath
self.shapeLayer?.add(basicAnimation, forKey: "path")
}
} else {
self.shapeLayer?.path = UIBezierPathUtils.customShapePath(rect: self.layer.bounds, cornersTriangleSize: cornerTriangleSize).cgPath
}
}
}