您的位置:首页 > 其它

CAKeyframeAnimation实现控件按照手势绘制的路径做动画

2016-04-08 20:51 369 查看


1.要绘制路径,需要自定义View

DrawView



//
//  DrawView.m

#import "DrawView.h"

@interface DrawView()

@property(nonatomic,strong)UIBezierPath *path;

@end

@implementation DrawView

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint currentP = [touch locationInView:self];

// 创建路径
UIBezierPath *path = [UIBezierPath bezierPath];
_path = path;

// 设置路径起点
[path moveToPoint:currentP];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint currentP = [touch locationInView:self];

// 添加点到当前路径
[_path addLineToPoint:currentP];

// 重绘
[self setNeedsDisplay];
}

/**
*  手指立刻,让控件按照我们绘制的路径做动画
*/
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//    // 创建动画
CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];

anim.keyPath = @"position";

anim.path = _path.CGPath;

anim.repeatCount = MAXFLOAT;
anim.duration = 1;

[[[self.subviews firstObject] layer] addAnimation:anim forKey:nil];
}

- (void)drawRect:(CGRect)rect
{
[_path stroke];
}

@end
注意,控制器里不要实现touch等方法,不然会被拦截
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: