Skip to content

Instantly share code, notes, and snippets.

@marty-suzuki
Created July 23, 2016 07:05
Show Gist options
  • Save marty-suzuki/026afd732a40d5fcdef796466bd08278 to your computer and use it in GitHub Desktop.
Save marty-suzuki/026afd732a40d5fcdef796466bd08278 to your computer and use it in GitHub Desktop.
@interface TriangleView()
@property (nonatomic, strong, readonly) CAShapeLayer *shapeLayer;
@end
@implementation TriangleView
static NSString *const kAniamtionKey = @"path";
static CGFloat const ANIMATION_DURATION = 0.25f;
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor clearColor];
_shapeLayer = [CAShapeLayer layer];
[self.layer addSublayer:self.shapeLayer];
[self.shapeLayer setFillColor:[UIColor yellowColor].CGColor];
[self.shapeLayer setStrokeColor:[UIColor blackColor].CGColor];
self.shapeLayer.path = [self trianglePathWithPoint:CGPointMake(0, self.frame.size.height)];
}
return self;
}
- (CGPathRef)trianglePathWithPoint:(CGPoint)point {
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointZero];
[path addLineToPoint:CGPointMake(self.frame.size.width, 0)];
[path addLineToPoint:point];
[path closePath];
return path.CGPath;
}
- (void)triangleAnimation:(CGPoint)point {
CGPathRef oldPath = self.shapeLayer.path;
CGPathRef newPath = [self trianglePathWithPoint:point];
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:kAniamtionKey];
[animation setFromValue:(__bridge id)oldPath];
[animation setToValue:(__bridge id)newPath];
[animation setDuration:ANIMATION_DURATION];
[animation setFillMode:kCAFillModeBackwards];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];
[self.shapeLayer addAnimation:animation forKey:kAniamtionKey];
self.shapeLayer.path = newPath;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint point = [[touches anyObject] locationInView:self];
[self triangleAnimation:point];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment