Wednesday, July 31, 2013

Animate Mask in Objective C

First of all you can view my masking image logic here


Now If i click the screen and want to animate this mask, then we can apply the below logic

-(void)moveLayer:(CALayer*)layer to:(CGPoint)point
    // Prepare the animation from the current position to the new position
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    animation.fromValue = [layer valueForKey:@"position"];
    animation.toValue = [NSValue valueWithCGPoint:point];
    animation.duration = .3;
    layer.position = point;
    [layer addAnimation:animation forKey:@"position"];

-(void)resizeLayer:(CALayer*)layer to:(CGSize)size
    CGRect oldBounds = layer.bounds;
    CGRect newBounds = oldBounds;
    newBounds.size = size;
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"bounds"];
    animation.fromValue = [NSValue valueWithCGRect:oldBounds];
    animation.toValue = [NSValue valueWithCGRect:newBounds];
    animation.duration = .3;
    layer.bounds = newBounds;    
    [layer addAnimation:animation forKey:@"bounds"];

- (UIImageView*) animateMaskedImage:(UIImage *)image withMasked:(UIImage *)maskImage width:(int )wd andHeight:(int )ht andSize:(CGSize)size andPosition:(CGPoint)pt {
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    CALayer *mask = [CALayer layer];
    mask.contents = (id)[maskImage CGImage];
    mask.frame = CGRectMake(0, 0, wd, ht);
    //Masking Animation
    [self resizeLayer:mask to:size];
    [self moveLayer:mask to:pt];
    imageView.layer.mask = mask;
    imageView.layer.masksToBounds = YES;
    return imageView;

Now we just need to call animatedMaskedImage function in our touch event like below

        [self.imageView1 removeFromSuperview];
        self.imageView1 = [self animateMaskedImage:self.image1 withMasked:self.mask1 width:1024 andHeight:768 andSize:CGSizeMake(1024*4, 768*4) andPosition:CGPointMake(1024*2, 768*2)];
        [self.completeSingleView addSubview:self.imageView1];

No comments:

Post a Comment