views:

312

answers:

3

Hey,

I would like to animate a curtain, which gets opened. I have two images: one for the left and one for the right side of the curtain (depicted in red). I would like to smoothly slide them away with Core Animation. For what animation type should I look for? How do I achieve a realistic sliding style?

Regards,

Stefan

alt text

+1  A: 

The easiest solution would be to have to imageview or CGLayers and then use CGAffineTransformTranslate in an animation block to slide them off screen.

TechZen
+2  A: 

I assume here that your curtains are UIImageViews...

-(void)CurtainAnimationFinished
    {
     //animationInProgress = NO;
    }

-(void)OpenCurtain
    { 
     //animationInProgress = YES;
     //UIImageView * rightCurtain;
     //UIImageView * leftCurtain;

     [UIView setAnimationDidStopSelector:@selector(CurtainAnimationFinished)];
     [UIView beginAnimations:@"OpenCurtain" context:nil];
     [UIView setAnimationDuration:0.5];//or desired time    

     int moveDistanceInPixels = 100;//desired distance that both curtains move away from their MEETING point (idealy make a #DEFINE)

     CGRect f = rightCurtain.frame;//ASSUMES BOTH CURTAINS HAVE SAME FRAME SIZE

     CGAffineTransform rightTranslate = CGAffineTransformMakeTranslation((f.origin.x+moveDistanceInPixels),f.origin.y); 
     CGAffineTransform leftTranslate = CGAffineTransformMakeTranslation((f.origin.x-moveDistanceInPixels)),f.origin.y); 

     rightCurtain.transform = rightTranslate;
     leftCurtain.transform = leftTranslate;

     [UIView commitAnimations];  
    }

Once you put the methods in your .h file you can call it within the same class with [self OpenCurtain];

To make a more realistic effect (so the curtains look like they are not solid) you could skew the image slightly to indicate that momentum is pulling the curtain back. Here is a good place to start.

Luke Mcneice
+2  A: 

I'm not sure why people are suggesting using a translation. If all you need to do is slide the images, simply call -setCenter on each image view inside an animation block. Like this:

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1.0];
[leftCurtainImageView setCenter:pointOffScreenLeft];
[rightCurtainImageView setCenter:pointOffScreenRight];
[UIView commitAnimations];

Where pointOffScreenLeft, and pointOffScreenRight are calculated something like:

CGPoint pointOffScreenLeft = CGPointMake(
                 -[leftCurtainImageView bounds].size.width, 
                 [leftCurtainImageView frame].origin.y);

CGPoint pointOffScreenRight = CGPointMake(
                 [rightCurtainImageView frame].origin.x + 
                 [rightCurtainImageView bounds].size.width, 
                 [leftCurtainImageView frame].origin.y);

These calculations assume that the curtains are positioned at the far left and far right edges respectively of their containing view.

Matt Long