Skip to content

Instantly share code, notes, and snippets.

@snown
Last active August 29, 2015 14:01
Show Gist options
  • Save snown/c560fe9edc6eedf94206 to your computer and use it in GitHub Desktop.
Save snown/c560fe9edc6eedf94206 to your computer and use it in GitHub Desktop.
Deceivingly simple answer to a view animation that keeps it's content in the same visual place as the view frame moves.
- (void)addAnimation:(CAAnimation *)anim forKey:(NSString *)key {
DDLogVerboseMethodCall(@" %@", [anim debugDescription]);
CAAnimation *finalAnim = anim;
if ([key isEqualToString:@"position"] && [anim isKindOfClass:[CABasicAnimation class]]) {
CABasicAnimation *contentsRectAnim;
CALayer *presentationLayer = [self presentationLayer];
if (presentationLayer) {
contentsRectAnim = [anim copy];
contentsRectAnim.keyPath = @"contentsRect";
contentsRectAnim.fromValue = [NSValue valueWithCGRect:self.contentsRect];
// Calculate the toValue for the contentsRect
CGRect newContentRect = presentationLayer.contentsRect;
newContentRect.origin.x += (self.position.x - presentationLayer.position.x) / self.bounds.size.width;
newContentRect.origin.y += (self.position.y - presentationLayer.position.y) / self.bounds.size.height;
contentsRectAnim.toValue = [NSValue valueWithCGRect:newContentRect];
[[self modelLayer] setContentsRect:newContentRect];
}
CAAnimationGroup *groupAnim = [CAAnimationGroup animation];
groupAnim.animations = @[anim, contentsRectAnim];
finalAnim = groupAnim;
}
[super addAnimation:finalAnim forKey:key];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment