iPhone animation problem SImulator vs Real Device - iphone

This is my first question her so please be gentle:
I have followig animation code running smoothly on the simulator as well as on the real device (I am testng on iPhone 3GS 3.1.2).
Animation is a simple transition between the 2 views, something like book page flipping.
One diffrence betwen simulator an real device (The problem I cannot investigate - solve) is that on real device when animation finishes - after rotation has been done animated view blink (show for a split of second) for a moment before it goes hidden. On the simulator this 'unexpected' blink does not happen.
Here is the animation code:
-(void)flip{
UIView *animatedView;
// create an animation to hold the page turning
CABasicAnimation *transformAnimation = [CABasicAnimation animationWithKeyPath:#"transform"];
transformAnimation.removedOnCompletion = NO;
transformAnimation.delegate = self;
transformAnimation.duration = ANIMATION_TIME;
transformAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
// this is the basic rotation by 90 degree along the y-axis
CATransform3D endTransform = CATransform3DMakeRotation(3.141f/2.0f,
0.0f,
-1.0f,
0.0f);
// these values control the 3D projection outlook
endTransform.m34 = 0.001f;
endTransform.m14 = -0.0015f;
// start the animation from the current state
transformAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
transformAnimation.toValue = [NSValue valueWithCATransform3D:endTransform];
animatedView = screenShot;
// Create an animation group to hold the rotation and possibly more complex animation in the future
CAAnimationGroup *theGroup = [CAAnimationGroup animation];
// Set self as the delegate to receive notification when the animation finishes
theGroup.delegate = self;
theGroup.duration = ANIMATION_TIME;
// CAAnimation-objects support arbitrary Key-Value pairs, we add the UIView tag
// to identify the animation later when it finishes
[theGroup setValue:[NSNumber numberWithInt:animatedView.tag] forKey:#"animated"];
// Here you could add other animations to the array
theGroup.animations = [NSArray arrayWithObjects:transformAnimation,nil];
theGroup.removedOnCompletion = NO;
// Add the animation group to the layer
if (animatedView.layer.anchorPoint.x != 0.0f)
{
animatedView.layer.anchorPoint = CGPointMake(0.0f, 0.5f);
float yy = animatedView.center.x - (animatedView.bounds.size.width / 2.0f);
animatedView.center = CGPointMake(yy, animatedView.center.y);
}
if(![animatedView isDescendantOfView:self.view])[self.view addSubview:animatedView];
screenShot.hidden = NO;
animatedView.hidden = NO;
[animatedView.layer addAnimation:theGroup forKey:#"flip"];
}
- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag {
screenShot.hidden = YES;
}

Try setting theGroup's and / or transformAnimation's fillMode to kCAFillModeForwards:
theGroup.fillMode = kCAFillModeForwards;
This should cause your animation to persist once its active duration has completed. I've used this to remove an end-of-animation flicker before.

Not sure I understand completely what you are seeing but it's possible you're seeing something caused by the speed difference between the device and the simulator. The simulator is considerably faster than the device so something that "blinks" very quickly might do so too fast for the human eye to catch on the simulator.

Oof. That's annoying. I think it is that there's a split-second between when animation stops and when that line of code executes. If only there were an animationWillStop: method! You might try, instead of screenShot.hidden = YES, screenShot.alpha = 0. I doubt it will make any difference speed-wise, but it might be worth a shot? You could also fade out the view as part of the animation, but I don't think you want to do that.
The only other thing I can think of is to setup an NSTimer with an interval just under your animation time. Something like:
[NSTimer scheduledTimerWithTimeInterval:(ANIMATION_TIME - .001) target:self selector:#selector(hideTheView) userInfo:nil repeats:NO];
And then implement that hideTheView method, of course.

Related

iOS "CABasicAnimation" brings component to the original position after animation complete

I'm animating UIImageView using iOS core animation "CABasicAnimation", all works fine for me but the only problem is when i animate to the position, after completeing animation it comes back to original position where it was. how can i overcome this? i need to keep UIImageView in moved position.
NOTE : I've seen few questions with success answers regarding this, but i have no idea why mine is not working like they say.
After rotating a CALayer using CABasicAnimation the layer jumps back to it's unrotated position
Here is my sample code,
CGPoint endPt = CGPointMake(160, 53);
CABasicAnimation *anim5 = [CABasicAnimation animationWithKeyPath:#"position"];
[anim5 setBeginTime:CACurrentMediaTime()+0.4];
anim5.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
anim5.fromValue = [NSValue valueWithCGPoint:imgRef.layer.position];
anim5.toValue = [NSValue valueWithCGPoint:endPt];
anim5.duration = 1.5;
anim5.speed = 2;
[imgRef.layer addAnimation:anim5 forKey:#"position"];
//this is what other answers ask to do
[anim5 setFillMode:kCAFillModeForwards];
[anim5 setRemovedOnCompletion:NO];
BTW [imgRef.layer setPosition:CGPointMake(160, 53)]; won't help me since i'm delaying animation with 4 milliseconds.
The root cause is that the animation just transitions the property between two values, it doesn't actually change the ending value. You need to change the ending value when the animation completes, there are three ways to do that.
1) Use the delegate property on the CAAnimation superclass to be notified of when the animation completes. At that point you can set the property to it's end value. See: https://developer.apple.com/library/mac/#documentation/GraphicsImaging/Reference/CAAnimation_class/Introduction/Introduction.html#//apple_ref/occ/cl/CAAnimation The animationDidStop:finished: is the method you'll need to implement on the delegate.
2) Set a completion block on the surrounding CATransaction. You'll need to manually start the CATransaction rather than having CABasicAnimation do that automatically for you. See: Objective-C - CABasicAnimation applying changes after animation?
3) See OMZ's comment below...
The right answer is to set the layer's position property, but as you've pointed out, it makes it more difficult because you're wanting a 0.4 second delay prior to the position change. Is there any reason you couldn't perform the delay first and then do the animation? Something like this:
- (IBAction)didTapMove:(id)sender
{
[self performSelector:#selector(animate) withObject:nil afterDelay:0.4];
}
- (void)animate
{
CGPoint endPt = CGPointMake(160, 53);
CABasicAnimation *anim5 = [CABasicAnimation animationWithKeyPath:#"position"];
anim5.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
anim5.fromValue = [NSValue valueWithCGPoint:_imageView.layer.position];
anim5.toValue = [NSValue valueWithCGPoint:endPt];
anim5.duration = 1.5;
anim5.speed = 2;
[_imageView.layer addAnimation:anim5 forKey:#"position"];
[_imageView.layer setPosition:CGPointMake(160, 53)];
}
Noticed I've removed your begin time from the animation since the delay is occurring in the perform selector call.

iOS; How to scale UIimageView (permanently) and then move it

I've hit a wall here. I know how to move an Image using "CGAffineTransformMakeTranslation" and I also know how to scale an image using"CGAffineTransformMakeScale" but for the life of me, I can't seem to get one Image to do both of these and stay that way. It scales to the desired size for about a split second and then immediately reverts to its original size and moves to the desired location. What I need is for the image to get big, STAY big, and then move to a new location (while permanently staying its new size).
Here is what I've got going on in my .m file:
-(IBAction)PushZoomButton {
[UIWindow animateWithDuration:1.5
animations:^{
JustinFrame.transform = CGAffineTransformMakeScale(2.0, 2.0);
JustinFrame.transform = CGAffineTransformMakeTranslation(10.0, 10.0);}];
[UIWindow commitAnimations];}
Any help with this would be appreciated!
you can use CGAffineTransformConcat, for instance:
JustinFrame.transform = CGAffineTransformConcat(CGAffineTransformMakeScale(2.0, 2.0), CGAffineTransformMakeTranslation(10.0, 10.0));
You may need to adapt the translation to (5, 5) since you have doubled the scale
The second transform you set overrides the first one. You need to concat both transform actions into one, as Luis said. Another way of writing that would be:
CGAffineTransform transform = CGAffineTransformMakeScale(2.0, 2.0);
transform = CGAffineTransformTranslate(transform, 10, 10);
JustinFrame.transform = transform;
You may need to look into CoreAnimation, basically what UIView animation is controlling under the hood. If you set up a CAAnimation, then what you want to achieve is done with the fillMode property of the animation.
Here's some example code to make a UIView look like it's opening like a door (copy pasted some code I have, but perhaps you could modify it and find it useful):
- (void) pageOpenView:(UIView *)viewToOpen duration:(NSTimeInterval)duration pageTurnDirection:(PageTurnDirection) p{
// Remove existing animations before stating new animation
[viewToOpen.layer removeAllAnimations];
// Make sure view is visible
viewToOpen.hidden = NO;
// disable the view so it’s not doing anythign while animating
viewToOpen.userInteractionEnabled = NO;
float dir = p == 0 ? -1.0f : 1.0f; // for direction calculations
// create an animation to hold the page turning
CABasicAnimation *transformAnimation = [CABasicAnimation animationWithKeyPath:#"transform"];
transformAnimation.removedOnCompletion = NO;
transformAnimation.duration = duration;
transformAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
CATransform3D startTransform = CATransform3DIdentity;
if (p == NEXT_PAGE) {
// orig values
startTransform.m34 = 0.001f;
}else {
// orig values
startTransform.m34 = -0.001f;
}
// start the animation from the current state
transformAnimation.fromValue = [NSValue valueWithCATransform3D:startTransform];
// this is the basic rotation by 90 degree along the y-axis
CATransform3D endTransform = CATransform3DMakeRotation(3.141f/2.0f,
0.0f,
dir,
0.0f);
// these values control the 3D projection outlook
if (p == NEXT_PAGE) {
endTransform.m34 = 0.001f;
endTransform.m14 = -0.0015f;
}else {
endTransform.m34 = -0.001f;
endTransform.m14 = 0.0015f;
}
transformAnimation.toValue = [NSValue valueWithCATransform3D:endTransform];
// Create an animation group to hold the rotation
CAAnimationGroup *theGroup = [CAAnimationGroup animation];
// Set self as the delegate to receive notification when the animation finishes
theGroup.delegate = self;
theGroup.duration = duration;
// CAAnimation-objects support arbitrary Key-Value pairs, we add the UIView tag
// to identify the animation later when it finishes
[theGroup setValue:[NSNumber numberWithInt:[(BODBookPageView *)viewToOpen pageNum]] forKey:#"animateViewPageNum"]; //STEPHEN: We set the tag to the page number
[theGroup setValue:[NSNumber numberWithInt: p] forKey:#"PageTurnDirection"];
[theGroup setValue:[NSNumber numberWithBool:YES] forKey:#"isAnimationMidpoint"]; // i.e. is this the first half of page-turning or not?
// Here you could add other animations to the array
theGroup.animations = [NSArray arrayWithObjects:transformAnimation, nil];
theGroup.removedOnCompletion = NO; // THIS LINE AND THE LINE BELOW WERE CRUCIAL TO GET RID OF A VERY HARD TO FIND/FIX BUG.
theGroup.fillMode = kCAFillModeForwards; // THIS MEANS THE ANIMATION LAYER WILL STAY IN THE STATE THE ANIMATION ENDED IN, THEREBY PREVENTING THAT ONE FRAME FLICKER BUG.
// Add the animation group to the layer
[viewToOpen.layer addAnimation:theGroup forKey:#"flipViewOpen"];
}

Is there an issue with updating a CALayer position while the layer is paused?

Is there an issue with reading the presentation position while it's paused?
I'm trying to pause and resume a CALayer. Once the CALayer is paused, I want to update the layer's position with it's current presentation position.
When I try do this, the layer flickers slightly once I resume the layer.
This is the code I'm using to pause and resume the CALayer (based on a Technical Q&A QA1673 supplied by Apple):
CFTimeInterval pausedTime;
void pauseLayer(CALayer *layer)
{
pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
layer.speed = 0.0;
layer.timeOffset = pausedTime;
layer.beginTime = 0;
// layer.position = ((CALayer*)[layer presentationLayer]).position;
}
void resumeLayer(CALayer *layer)
{
layer.speed = 1.0;
layer.timeOffset = 0.0;
layer.beginTime = 0.0;
CFTimeInterval _elapsedTimeSincePaused = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
layer.beginTime = _elapsedTimeSincePaused;
}
If I uncomment the layer.position = ((CALayer*)[layer presentationLayer]).position; in pauseLayer, the layer flickers once I call resumeLayer.
This is my animation code:
- (void) startAnimation:(id)sender
{
layer10Animation = [CABasicAnimation animationWithKeyPath:#"position.x"];
layer10Animation.duration = 1;
layer10Animation.toValue = [NSNumber numberWithInt:300];
layer10Animation.fromValue = [NSNumber numberWithInt:20];
layer10Animation.repeatCount = 100;
layer10Animation.autoreverses = YES;
[layer10 addAnimation:layer10Animation forKey:nil];
}
Best regards
There's not an issue with updating aCALayerposition whilst it's paused. Naturally however it will give the flicker that you mention. That's because you are updating the layer's position mid animation.
Don't forget that creating aCABasicAnimationand adding it to aCALayerdoesn't change the layer's settings. It creates an animation using the layer, but it doesn't change the layer.
That's why after the animation has finished, you'll see the layer back in exactly the same position it was before.
Because of this, if you are animating a layer from A to B, if you want the layer to appear at B after the animation has finished, you'll need this delegate callback:
- (void)animationDidStart:(CAAnimation *)theAnimation
{
[CATransaction begin];
[CATransaction setValue:(id)kCFBooleanTrue
forKey:kCATransactionDisableActions];
myLayer.position = targetPosition;
[CATransaction commit];
}
Yep, it'sanimationDidStart. If we did it usinganimationDidStopthen you would see another flicker. The layer would be in the animation's end position of B, then you'd see a flicker of it at A, and then you'd see it at B again.
UsinganimationDidStartwe set the position to be thetargetPosition, i.e.B because that's where we want to see it on completion.
Now, regarding QA1673, what you are doing with this is setting the animation speed to zero, and getting a timestamp of the currentCACurrentMediaTime(). On resume, you put the speed back to normal, and apply any offsets incurred during the pause time.
This all seems pretty confusing until you get the hang of it. Could I recommend some reading and videos?
Definitely have a read of Core Animation Rendering Architecture.
Videos that are highly recommended are:
WWDC 2010 Sessions 424 and 425 Core Animation in Practice Parts 1 and 2
WWDC 2011 Session 421 Core Animation Essentials
and
Developer Videos Session 716 Core Animation Techniques for iPhone and Mac

Non-Smooth animation with Core Animation

This is a weird request, but I'm using Core Animation (CALayers), and I want my animation to be choppy and non-smooth. I want an image I set up to rotate like a second hand on a clock. Here's my code:
UIImage *arrowImage = [UIImage imageNamed:#"arrow.jpg"];
CALayer *arrow = [CALayer layer];
arrow.contents = (id)arrowImage.CGImage;
arrow.bounds = CGRectMake(0, 0, 169.25, 45.25);
arrow.position = CGPointMake(self.view.bounds.size.width / 2, arrowImage.size.height / 2);
arrow.anchorPoint = CGPointMake(0.0, 0.5);
[self.view.layer addSublayer:arrow];
CABasicAnimation *anim1 = [CABasicAnimation animationWithKeyPath:#"transform.rotation"];
anim1.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
anim1.fromValue = [NSNumber numberWithFloat:0];
anim1.toValue = [NSNumber numberWithFloat:((360*M_PI)/180)];
anim1.duration = 4.0;
[arrow addAnimation:anim1 forKey:#"transform"];
It produces a gliding motion, which I don't want. How do I get around this?
Any help is appreciated.
If you want it to be really choppy, don't use Core Animation at all. On the other hand, if you want something somewhere in between those two extremes, don't use linear media timing. Instead, you might want to try kCAMediaTimingFunctionEaseIn so that the animation accelerates slightly as the hand moves.
The simple way to do this would be to simply apply a transform to your view. The second hand would snap from one position to the next. Just change the rotation by 360/60 = 6 degrees for each second.
If you want the second-hand to do an animation for each tick, you could use a very fast UIView block-based animation. (say with a 1/15 second duration or so.)
Take a look at the UIView class methods who's names start with animateWithDuration.
Something like this:
- (void) moveSecondHand;
{
seconds++;
angle = M_PI*2*seconds/60 - M_PI/2;
CGAffineTransform transform = CGAffineTransformMakeRotation(angle);
[UIView animateWithDuration: 1.0/15
animations: *{
secondHand.transform = transform
}];
}
That's about all it would take. You're trigger that code with a timer once a second. By default animations use ease-in, ease-out timing, which models physical movement pretty well. Try different durations, but 1/15 is probably a good starting point (you want it fast, but not too fast to see.)
If you want a wobble to your animation you will need to get much fancier, and create an animation group that first moves it by the full amount, and then does a repeating animation that overshoots the stopping point by a small amount and then goes back.

How do I chain scale animations with an iPhone UIImageView?

I'm trying to scale an image down, change the image, then scale it back up.
CABasicAnimation* shrink = [CABasicAnimation animationWithKeyPath:#"transform.scale"];
shrink.toValue = [NSNumber numberWithDouble:0];
shrink.duration = 1;
shrink.delegate = self;
[myImageView.layer addAnimation:shrink forKey:#"shrink"];
makes the shrink, then when it completes, I change the image, and start the grow:
- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag
{
myImageView.image = [images objectAtIndex:image];
CABasicAnimation* grow = [CABasicAnimation animationWithKeyPath:#"transform.scale"];
grow.toValue = CGAffineTransformMakeScale(1,1);
grow.delegate = self;
grow.duration = 1;
[myImageView.layer addAnimation:grow forKey:#"grow"];
}
This works great on the simulator, but on the device, when the shrink completes, I get a flash of the full-size, old image, then the grow animation begins with the new image.
Any idea how to get rid of that flash?
(I've tried "removedOnCompletion = NO;" and attempted setting the affineTransform equal to the scaled down size after the first completion, but didn't have much luck.)
Any tips appreciated.
kb
Edit:
Excellent! Setting the following:
shrink.fillMode = kCAFillModeForwards;
shrink.removedOnCompletion = NO;
Removed the flashing. Thanks, Ben!
Try setting your animation's fillMode to kCAFillModeForwards. That should leave the item as it was at the end of the animation, rather than before.
I've had the same problem when I tried to create another CAAnimation in the animationDidStop method. I suggest using CAKeyframeAnimation.