Search code examples
iosobjective-canimationuiviewcore-animation

How to create Custom flip animation using UIView


I am trying to create a custom animation something like the default flip animation for a UIView, but without the actual flip, and also the axis of the flip I want to be on the left side not on the center. Here is an example of what I am trying to accomplish but without the repeat:

enter image description here

Also in the code I will add UILabel as sub view and a few more elements.

If you can provide a code example it will be much appreciated Thank you very much in advance for any support!

Update:

used the example provided by @artal and obtained the wanted effect for UIImageView but how can I obtain the same example for an UIButton?

Tried the next code:

objectivesButton = [[UIButton alloc] initWithFrame:CGRectMake( 0.25f * [UIScreen mainScreen].bounds.size.width, 0.7f * [UIScreen mainScreen].bounds.size.height, 0.5f * [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height * 0.3f)];
[objectivesButton addTarget:self
                action:@selector(startAnimationButton)
      forControlEvents:UIControlEventTouchUpInside];
objectivesButton.backgroundColor = [UIColor yellowColor];
objectivesButton.layer.anchorPoint = CGPointMake(0, 0.5);
[self.view addSubview:objectivesButton];

- (void)startAnimationButton{

CATransform3D perspectiveTrasnform = CATransform3DIdentity;
perspectiveTrasnform.m34 = -0.004;

CGFloat rotateAngleDeg = 90;
CATransform3D flipTransform = CATransform3DRotate(perspectiveTrasnform, rotateAngleDeg / 180.0 * M_PI, 0, 1.5, 0);
[UIView animateWithDuration:3.0f animations:^()
{
    objectivesButton.layer.transform = flipTransform;
}];

}

Solution

  • You can animate the view this way by applying a perspective and rotation transform to its underlying CALayer (a 3D transform). To start it from the left side you can set the anchorPoint of the layer. Here's an example:

    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.png"]];
    imageView.center = CGPointMake(self.view.center.x - imageView.frame.size.width * 0.5, self.view.center.y + imageView.frame.size.height * 0.5);
    imageView.layer.anchorPoint = CGPointMake(0, 1);
    [self.view addSubview:imageView];
    
    CATransform3D perspectiveTrasnform = CATransform3DIdentity;
    perspectiveTrasnform.m34 = -0.004;
    
    CGFloat rotateAngleDeg = 90;
    CATransform3D flipTransform = CATransform3DRotate(perspectiveTrasnform, rotateAngleDeg / 180.0 * M_PI, 0, 1, 0);
    [UIView animateWithDuration:5 animations:^()
    {
        imageView.layer.transform = flipTransform;
    }];