Skip to content

Instantly share code, notes, and snippets.

@chrismiles
Created March 14, 2011 07:35
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chrismiles/868878 to your computer and use it in GitHub Desktop.
Save chrismiles/868878 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:
double currentProgress = 1.0;
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"currentProgress"];
anim.duration = 0.5;
anim.fromValue = [NSNumber numberWithDouble:0.0];
anim.toValue = [NSNumber numberWithDouble:currentProgress];
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
[myLayer addAnimation:anim forKey:@"animateProgress"];
myLayer.currentProgress = currentProgress;
*/
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
@interface MyLayer : CALayer {
double currentProgress;
}
@property (nonatomic, assign) double currentProgress;
@end
@implementation MyLayer
@synthesize currentProgress;
+ (BOOL)needsDisplayForKey:(NSString *)key {
// To force animation when our custom properties change
BOOL result;
if ([key isEqualToString:@"currentProgress"]) {
result = YES;
}
else {
result = [super needsDisplayForKey:key];
}
return result;
}
- (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