Moving an image along a series of CGPoints - iphone

I have path stored in an array of CGPoints which I'd like to move an image along. Here's the general code I have so far:
-(void)movePic:(id)sender{
for(int i = 0; i < self.array.count; i++){
CGPoint location = [[self.array objectAtIndex:i] CGPointValue];
[UIView animateWithDuration:0.1 animations:^{
self.imageView.center = location;
} completion:^(BOOL finished){
}];
}
}
The problem is the for loop runs extremely fast, so you only see the animation on the last points. I'm unsure of how to better design this. Ideally, what could I do to make sure one animation finishes before the other begins? Should I not use a for loop? Thanks

Your code assumes that UIView animations run synchronously in the main thread, which they do not.
You seem to have two options
Explicit CAKeyframeAnimation for animating a CALayer along any amount of sample points (interpolated between them)
Implicit recursive UIView animation for animating a UIView along a series of sample points (interpolated between them)
The former would be much more efficient - still I thought I oould show you both options.
CAKeyframeAnimation
- (void)movePic:(id)sender
{
//create a mutable core-graphics path
CGMutablePathRef path = CGPathCreateMutable();
for(int i = 0; i < self.array.count; i++)
{
CGPoint location = [[self.array objectAtIndex:index] CGPointValue];
CGPathAddLineToPoint(path, nil, location.x, location.y);
}
//create a new keyframe animation
CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:#"position"];
//add our path to it
pathAnimation.path = path;
//be nice to the system
CGPathRelease(path);
//setup some more animation parameters
pathAnimation.duration = 0.1 * self.array.count;
//add the animation to our imageView's layer (which will start the animation)
[self.imageView.layer addAnimation:pathAnimation forKey:#"pathAnimation"];
}
UIView Animation
- (void)movePicToPointAtIndex:(unsigned int)index
{
//safeguard check...
if ([self.array count] <= index)
return;
//get the next location
CGPoint location = [[self.array objectAtIndex:index] CGPointValue];
//animate the imageView center towards that location
[UIView animateWithDuration:0.1
delay:0.0
options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionAllowUserInteraction
animations:^{
self.imageView.center = location;
} completion:^(BOOL finished){
//we are done with that animation, now go to the next one...
[self movePicToPointAtIndex:index+1];
}];
}
- (void)movePic:(id)sender
{
[self movePicToPointAtIndex:0];
}

Ok, the thing you have to do is set the array of points as a property of the class, something like animationPath. Ok, so now you would have to pay attention to the delegate methods of the UIView animation delegate methods (it's not actually a different class, it's just a delegate of the class' methods).
Set a method to call on setAnimationDidStopSelector:selector every time the animation stops, so here you would have something like this:
//Inside the callback for setAnimationDidStopSelector
if ([animationPath count] != 0){
//Go to next point
CGPoint location = [[self.array objectAtIndex:0] CGPointValue];
[UIView animateWithDuration:0.1 animations:^{
self.imageView.center = location;
} completion:^(BOOL finished){
}];
}
else{
NSLog(#"Nowhere else to go, animation finished :D");
}
So just be sure to fire your animation with the first point.
As far as I remember UIViews animations manage things in other threads so that's probably why the for statement is not working.

Related

UIScrollView with fadeIn/fadeOut effect

I've scrollview with page control and I want to make the subview of my scrollview fadeIn/fadeOut when I scroll to or from the next page. I found that I can use contentOffset to make this effect but I couldn't make it.
In fact, I'm newbie and I wish If there is any tutorial that can help. thank you.
Assuming you hold an array of your view controllers in self.viewControllers indexed according to the UIPageControl:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat diffFromCenter = ABS(scrollView.contentOffset.x - (self.pageControl.currentPage)*self.view.frame.size.width);
CGFloat currentPageAlpha = 1.0 - diffFromCenter/self.view.frame.size.width;
CGFloat sidePagesAlpha = diffFromCenter/self.view.frame.size.width;
//NSLog(#"%f",currentPageAlpha);
[[[self.viewControllers objectAtIndex:self.pageControl.currentPage] view] setAlpha:currentPageAlpha];
if (self.pageControl.currentPage > 0)
[[[self.viewControllers objectAtIndex:self.pageControl.currentPage-1] view] setAlpha:sidePagesAlpha];
if (self.pageControl.currentPage < [self.viewControllers count]-1)
[[[self.viewControllers objectAtIndex:self.pageControl.currentPage+1] view] setAlpha:sidePagesAlpha];
}
You might check out this tutorial on view animation:
Uiview-tutorial-for-ios-how-to-use-uiview-animation
To achieve the effect you are looking for you can use something like this:
ScrollView delegate method to detect scrolling (if your only paging)
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
UIView* subView = [scrollView.subviews lastObject]; //Or however you access your subview
[UIView animateWithDuration:1.0f animations:^{
subView.alpha = 0.0f;
} completion:^(BOOL finished){
[UIView animateWithDuration:1.0f animations:^{
subView.alpha = 1.0f;
}];
}];
}
This will cause your subview to smoothly fade out and in within the span of 2.0 seconds. You should a bit of reading about this animation blocks though as they can be a little tricky. For instance I had nest the second animation block after the first had complete because the actual code within them is handled immediately and the animation simply takes place on the View side of things.
Hope this helps!
You can fade it to zero, change the contentOffset without animation, and fade it back to alpha with 1.0:
- (IBAction)didChangePageView:(id)sender
{
[UIView animateWithDuration:0.25
animations:^{
self.scrollView.alpha = 0.0;
}
completion:^(BOOL finished) {
[self.scrollView setContentOffset:CGPointMake(0, self.scrollView.frame.size.height * self.pageViewControl.currentPage) animated:NO];
[UIView animateWithDuration:0.25 animations:^{
self.scrollView.alpha = 1.0;
}];
}];
}
With Swift 2.0, assuming you hold an array of your subViews in myViewsArray:
func scrollViewDidScroll(scrollView: UIScrollView) {
//Fade in/out effect while scrolling
for (index,subView) in myViewsArray.enumerate() {
label.alpha = 1 - abs(abs(scrollView.contentOffset.x) - subView.frame.width * CGFloat(index)) / subView.frame.width
}
}

Oscillating UIView With Stopping Motion (iOS)

I need a view to enter the screen with oscillating animation and finally, the animation should stop in a natural way (decreasing oscillations - pendulum effect). I have added the subview above the screen so that the view rotates into the screen when required. The code for adding the subview is:
myView.layer.anchorPoint = CGPointMake(1.0, 0.0);
[[self view] addSubview:myView];
[myView setHidden:YES];
// Rotate 75 degrees to hide it off screen
CGAffineTransform rotationTransform = CGAffineTransformIdentity;
rotationTransform = CGAffineTransformRotate(rotationTransform, DEGREES_RADIANS(75));
bannerView.transform = rotationTransform;
bannerView.center = CGPointMake(((self.view.bounds.size.width)/2.0), -5.0);
[self performSelector:#selector(animateSwing) withObject:nil afterDelay:3.0];
The way I'm trying to achieve this that the view should rotate one full semi circle & back rotation, then rotate one semi circle rotation and finally come to halt at desired point using EaseOut animation curve. The code for my animateSwing() method is given below:
- (void)animateSwing {
NSLog(#"ANIMATING");
[myView setHidden:NO];
CGAffineTransform swingTransform = CGAffineTransformIdentity;
swingTransform = CGAffineTransformRotate(swingTransform, DEGREES_RADIANS(-20));
[UIView animateWithDuration:0.30
delay:0.0
options:UIViewAnimationOptionCurveEaseOut
animations:^{
[UIView setAnimationRepeatCount:1.5];
[UIView setAnimationRepeatAutoreverses:YES];
myView.transform = swingTransform;
}completion:^(BOOL finished){
[UIView animateWithDuration:0.10
delay:0.0
options:UIViewAnimationOptionCurveEaseOut
animations:^{
myView.transform = CGAffineTransformMakeRotation(DEGREES_RADIANS(0));
}completion:^(BOOL Finished){
}];
}];
}
For some reason the above code isn't working. If I do not chain animations, the code performs the semi-circle routine. But if I chain animations like above, it just oscillates a little bit around the desired point and ends abruptly.
Please suggest a fix to this code OR suggest a way to implement the required animation
Thanks
You want to use a keyframe animation. I actually have an example of a "decreasing waggle" animation in my book (http://www.apeth.com/iOSBook/ch17.html#_keyframe_animation):
CompassLayer* c = (CompassLayer*)self.compass.layer;
NSMutableArray* values = [NSMutableArray array];
[values addObject: #0.0f];
int direction = 1;
for (int i = 20; i < 60; i += 5, direction *= -1) { // alternate directions
[values addObject: #(direction*M_PI/(float)i)];
}
[values addObject: #0.0f];
CAKeyframeAnimation* anim =
[CAKeyframeAnimation animationWithKeyPath:#"transform"];
anim.values = values;
anim.additive = YES;
anim.valueFunction =
[CAValueFunction functionWithName: kCAValueFunctionRotateZ];
[c.arrow addAnimation:anim forKey:nil];
Of course that isn't identical to what you're trying to do, but it should get you started.

iphone development: how to create an animation by using NSTimer

In my app I have this code in viewWillAppear. It simply animates random object from top of the screen to the bottom. The problem is I need to detect collision and what I have learnt so far is it is impossible to retrieve the coordinates at any time for an animation. so how can I implement it by using NSTimer? or shall I use NSTimer? I could not figure it out. Any clue will be appreciated.
-(void)viewWillAppear:(BOOL)animated
{
for (int i = 0; i < 100; i++) {
p = arc4random_uniform(320)%4+1;
CGRect startFrame = CGRectMake(p*50, -50, 50, 50);
CGRect endFrame = CGRectMake(p*50, CGRectGetHeight(self.view.bounds) + 50,
50,
50);
animatedView = [[UIView alloc] initWithFrame:startFrame];
animatedView.backgroundColor = [UIColor redColor];
[self.view addSubview:animatedView];
[UIView animateWithDuration:2.f
delay:i * 0.5f
options:UIViewAnimationCurveLinear
animations:^{
animatedView.frame = endFrame;
} completion:^(BOOL finished) {
[animatedView removeFromSuperview];
}];
}
I would ditch NSTimer for CADisplayLink to send a message to your target. NSTimer can cause stuttering animations since it doesn't synchronize with the device's screen refresh rate. CADisplayLink does exactly that and makes your animations run like butter.
Documentation:
http://developer.apple.com/library/ios/#documentation/QuartzCore/Reference/CADisplayLink_ClassRef/Reference/Reference.html
Ultimately, using CADisplayLink looks something like this:
- (id) init {
// ...
CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:#selector(update:)];
[displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
// ...
}
- (void) update {
[myView updatePositionOrSomethingElse];
}
Your statement:
is it is impossible to retrieve the coordinates at any time for an
animation
seems incorrect did you check this?
It looks like you can use the CALayer's presentationLayer property to extract coordinates info during an animation:
CGRect movingFrame = [[yourView.layer presentationLayer] frame];
I will use this info to check time to time if there is a collision during the animation. So I will use the timer to check the collision status not for animating the views.
You can have your objects animate in small increments (in a loop may be). Every time you complete your animation, you can get the coordinates.
I think you could use the beginAnimations - commitAnimations syntax in a for cycle it could count for eg. till 10, so after each cycle you can check for collision
CGRect incrementedViewFrame;
for(int i = 0; i < 10; ++i)
{
incrementedViewFrame = CGRectMake(/*calculate the coords here*/);
if(collision)
{
//do stuff
}
else
{
//do an other animation cycle
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.1f];
[[self viewToAnimate]setFrame:incrementedViewFrame];
[UIView commitAnimations];
}
}
I hope that helps!

iPhone SDK: Flip-and-scale animation between view controllers using blocks?

I'm trying to create a flip-and-scale animation between two view controllers. This seems possible using animation blocks available in iOS 4.0, but I'm still unsure how to implement it. I found this SO question which shows a flip animation.
Using this code, flipping between two views works fine, but scaling doesn't -- the flip animation completes and then the new view jumps to the correct size. How would I flip the view and scale it at the same time?
UIView *tempContainer = myView.contentView ;
[UIView transitionWithView:tempContainer
duration:2
options:UIViewAnimationOptionTransitionFlipFromRight
animations:^{
[[[tempContainer subviews] objectAtIndex:0] removeFromSuperview];
[tempContainer addSubview:myOtherViewController.view];
CGAffineTransform transform = CGAffineTransformMakeScale(4.0, 4.0);
tempContainer.transform = transform;
}
completion:^(BOOL finished){
[tempContainer release];
}];
I suppose this happens because the option UIViewAnimationOptionTransitionFlipFromRight somehow overrides everything else. Try using nesting animations or link them together
Here's how I flip and scale between two views of different sizes. I break the animation into a few parts. First I put the back view at the same location as the front view, but make it hidden. I then flip and scale the front view halfway. The back view is given the same transform as the front view, then rotated and scaled the rest of the way. Flipping back is basically the reverse.
I suppose you could use a different view controllers view property as the back view, but I haven't tried that.
// flip and scale frontView to reveal backView to the center of the screen
// uses a containerView to mark the end of the animation
// parameterizing the destination is an exercise for the reader
- (void)flipFromFront:(UIView*)frontView toBack:(UIView*)backView destination:(CGRect)destRect
{
float duration = 0.5;
// distance from center of screen from frontView
float dx = destRect.origin.x + CGRectGetWidth(destRect) / 2 - frontView.center.x;
float dy = destRect.origin.y + CGRectGetHeight(destRect) / 2 - frontView.center.y;
float scale = CGRectGetWidth(destRect) / CGRectGetWidth(frontView.bounds);
// this prevents any tearing
backView.layer.zPosition = 200.0;
// hide the backView and position where frontView is
backView.hidden = NO;
backView.alpha = 0.0;
backView.frame = frontView.frame;
// start the animation
[UIView animateKeyframesWithDuration:duration
delay:0.25
options:UIViewKeyframeAnimationOptionCalculationModeCubic
animations:^{
// part 1. Rotate and scale frontView halfWay.
[UIView addKeyframeWithRelativeStartTime:0.0
relativeDuration:0.5
animations:^{
// get the transform for the blue layer
CATransform3D xform = frontView.layer.transform;
// translate half way
xform = CATransform3DTranslate(xform, dx/2, dy/2, 0);
// rotate half way
xform = CATransform3DRotate(xform, M_PI_2, 0, 1, 0);
// scale half way
xform = CATransform3DScale(xform, scale/2, scale/2, 1);
// apply the transform
frontView.layer.transform = xform;
}];
// part 2. set the backView transform to frontView so they are in the same
// position.
[UIView addKeyframeWithRelativeStartTime:0.5
relativeDuration:0.0
animations:^{
backView.layer.transform = frontView.layer.transform;
backView.alpha = 1.0;
}];
// part 3. rotate and scale backView into center of container
[UIView addKeyframeWithRelativeStartTime:0.5
relativeDuration:0.5
animations:^{
// undo previous transforms with animation
backView.layer.transform = CATransform3DIdentity;
// animate backView into new location
backView.frame = destRect;
}];
} completion:^(BOOL finished) {
self.displayingFront = !self.displayingFront;
}];
}
// flip from back to front
- (void) flipFromBack:(UIView*)backView toFront:(UIView*)frontView
{
float duration = 0.5;
// get distance from center of screen to destination
float dx = backView.center.x - frontView.center.x;
float dy = backView.center.y - frontView.center.y;
backView.layer.zPosition = 200.0;
frontView.hidden = YES;
// this is basically the reverse of the previous animation
[UIView animateKeyframesWithDuration:duration
delay:0
options:UIViewKeyframeAnimationOptionCalculationModeCubic
animations:^{
[UIView addKeyframeWithRelativeStartTime:0.0
relativeDuration:0.5
animations:^{
CATransform3D xform = backView.layer.transform;
xform = CATransform3DTranslate(xform, -dx/2, -dy/2, 0);
xform = CATransform3DRotate(xform, M_PI_2, 0, 1, 0);
xform = CATransform3DScale(xform, 0.75, 0.75, 1);
backView.layer.transform = xform;
}];
[UIView addKeyframeWithRelativeStartTime:0.5
relativeDuration:0.0
animations:^{
backView.alpha = 0.0;
frontView.hidden = NO;
}];
[UIView addKeyframeWithRelativeStartTime:0.5
relativeDuration:0.5
animations:^{
self.hiddenView.alpha = 0.0;
frontView.layer.transform = CATransform3DIdentity;
}];
} completion:^(BOOL finished) {
self.displayingFront = !self.displayingFront;
}];
}

How to specify selector when CAKeyframeAnimation is finished?

I'm using a CAKeyframeAnimation to animate a view along a CGPath. When the animation is done, I'd like to be able to call some other method to perform another action. Is there a good way to do this?
I've looked at using UIView's setAnimationDidStopSelector:, however from the docs this looks like it only applies when used within a UIView animation block (beginAnimations and commitAnimations). I also gave it a try just in case, but it doesn't seem to work.
Here's some sample code (this is within a custom UIView sub-class method):
// These have no effect since they're not in a UIView Animation Block
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(animationDidStop:finished:context:)];
// Set up path movement
CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:#"path"];
pathAnimation.calculationMode = kCAAnimationPaced;
pathAnimation.fillMode = kCAFillModeForwards;
pathAnimation.removedOnCompletion = NO;
pathAnimation.duration = 1.0f;
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, self.center.x, self.center.y);
// add all points to the path
for (NSValue* value in myPoints) {
CGPoint nextPoint = [value CGPointValue];
CGPathAddLineToPoint(path, NULL, nextPoint.x, nextPoint.y);
}
pathAnimation.path = path;
CGPathRelease(path);
[self.layer addAnimation:pathAnimation forKey:#"pathAnimation"];
A workaround I was considering that should work, but doesn't seem like the best way, is to use NSObject's performSelector:withObject:afterDelay:. As long as I set the delay equal to the duration of the animation, then it should be fine.
Is there a better way? Thanks!
Or you can enclose your animation with:
[CATransaction begin];
[CATransaction setCompletionBlock:^{
/* what to do next */
}];
/* your animation code */
[CATransaction commit];
And set the completion block to handle what you need to do.
CAKeyframeAnimation is a subclass of CAAnimation. There is a delegate property in CAAnimation. The delegate can implement the -animationDidStop:finished: method. The rest should be easy.
Swift 3 syntax for this answer.
CATransaction.begin()
CATransaction.setCompletionBlock {
//Actions to be done after animation
}
//Animation Code
CATransaction.commit()