Skip to content

Instantly share code, notes, and snippets.

@mralexgray
Forked from chrismiles/MyLayer.m
Created October 27, 2012 16:30
Show Gist options
  • Save mralexgray/3965251 to your computer and use it in GitHub Desktop.
Save mralexgray/3965251 to your computer and use it in GitHub Desktop.
Animate a custom property in a CALayer example.
//
// MyLayer.m
//
// Created by Chris Miles on 14/03/11.
// Copyright 2011 Chris Miles.
//
/*
Animate custom property example:
CGFloat currentProgress = 1.0;
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"currentProgress"];
anim.duration = 0.5;
anim.fromValue = @0;
anim.toValue = @(currentProgress);
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
[myLayer addAnimation:anim forKey:@"animateProgress"];
myLayer.currentProgress = currentProgress;
*/
#import <Cocoa/Cocoa.h>
#import <QuartzCore/QuartzCore.h>
@interface MyLayer : CALayer
@property (nonatomic, assign) CGFloat currentProgress;
@end
@implementation MyLayer
@synthesize currentProgress;
+ (BOOL)needsDisplayForKey:(NSString *)key {
// To force animation when our custom properties change
return [key isEqualToString:@"currentProgress"]
?: [super needsDisplayForKey:key];
}
- (void)setCurrentProgress:(double)progress {
// Force redraw outside of animations
currentProgress = progress;
[self setNeedsDisplay];
}
- (void)drawInContext:(CGContextRef)c {
// Custom layer drawing
}
- (id)initWithLayer:(id)layer {
if ((self = [super initWithLayer:layer])) {
if ([layer isKindOfClass:[MyLayer class]]) {
// Copy custom property values between layers
MyLayer *other = (MyLayer *)layer;
self.currentProgress = other.currentProgress;
}
}
return self;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment