adding bounce effect to appearance of UIImageView
Bouncy (expand/shrink) animation in Swift:
var selected: Bool {
willSet(selected) {
let expandTransform:CGAffineTransform = CGAffineTransformMakeScale(1.2, 1.2);
if (!self.selected && selected) {
self.imageView.image = SNStockCellSelectionAccessoryViewImage(selected)
self.imageView.transform = expandTransform
UIView.animateWithDuration(0.4,
delay:0.0,
usingSpringWithDamping:0.40,
initialSpringVelocity:0.2,
options: .CurveEaseOut,
animations: {
self.imageView.transform = CGAffineTransformInvert(expandTransform)
}, completion: {
//Code to run after animating
(value: Bool) in
})
}
}
}
var imageView:UIImageView
If imageView
is correctly added to the view as a subview, toggling between selected = false
to selected = true
should swap the image with a bouncy animation. SNStockCellSelectionAccessoryViewImage
just returns a different image based on the current selection state, see below:
private let SNStockCellSelectionAccessoryViewPlusIconSelected:UIImage = UIImage(named:"PlusIconSelected")!
private let SNStockCellSelectionAccessoryViewPlusIcon:UIImage = UIImage(named:"PlusIcon")!
private func SNStockCellSelectionAccessoryViewImage(selected:Bool) -> UIImage {
return selected ? SNStockCellSelectionAccessoryViewPlusIconSelected : SNStockCellSelectionAccessoryViewPlusIcon
}
The GIF example below is a bit slowed down, the actual animation happens faster:
y-axis animation using CABasicAnimation:
CGPoint origin = self.imageView.center;
CGPoint target = CGPointMake(self.imageView.center.x, self.imageView.center.y+100);
CABasicAnimation *bounce = [CABasicAnimation animationWithKeyPath:@"position.y"];
bounce.duration = 0.5;
bounce.fromValue = [NSNumber numberWithInt:origin.y];
bounce.toValue = [NSNumber numberWithInt:target.y];
bounce.repeatCount = 2;
bounce.autoreverses = YES;
[self.imageView.layer addAnimation:bounce forKey:@"position"];
If you want to implement shrink and grow you have to add a CGAffineTransformMakeScale, eg:
// grow
CGAffineTransform transform = CGAffineTransformMakeScale(1.3, 1.3);
imageView.transform = transform;
[UIView animateWithDuration:0.8
delay:0
usingSpringWithDamping:0.5
initialSpringVelocity:0.5
options:(UIViewAnimationOptionAutoreverse|
UIViewAnimationOptionRepeat)
animations:^{
CGRect frame = view.frame;
frame.origin.y -= 8;
view.frame = frame;
} completion:nil];
Play with the values to get different effects.