本文是吸附特效的一个小Demo:
UIAttachmentBehavior
iOS7开始的技术。 提供了一个模拟真实世界中力学相关的动画和交互系统,比如,重力、碰撞、吸附等
效果:
鼠标拖拽吸附点,释放后,滑块摆动…….
实现思路:
1.添加拖拽UIPanGestureRecognizer手势
- (IBAction)tap:(UIPanGestureRecognizer *)sender {
CGPoint location = [sender locationInView:self.view];
//将手势滑动到的点作为吸附行为的锚点
self.attachment.anchorPoint = location;
}
2.重写场景、重力、吸附的getter方法
@property(nonatomic,strong)UIDynamicAnimator *animator;
@property(nonatomic,strong)UIGravityBehavior *gravity;
@property(nonatomic,strong)UIAttachmentBehavior *attachment;
- (UIDynamicAnimator *)animator{
if (!_animator) {
_animator = [[UIDynamicAnimator alloc]initWithReferenceView:self.view];
}
return _animator;
}
- (UIGravityBehavior *)gravity{
if (!_gravity) {
_gravity = [[UIGravityBehavior alloc]initWithItems:@[self.imageView]];
}
return _gravity;
}
- (UIAttachmentBehavior *)attachment{
CGPoint attachmentAnchor = CGPointMake(self.imageView.center.x, self.imageView.center.y - 100);
if (!_attachment) {
_attachment = [[UIAttachmentBehavior alloc]initWithItem:self.imageView attachedToAnchor:attachmentAnchor];
}
return _attachment;
}
3.利用贝塞尔曲线绘制锚点到中心点的悬挂的线,并注意将特效添加到场景中。
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self.animator addBehavior:self.gravity];
self.attachment.action = ^{
//绘制锚点到中心点的悬挂的线
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:self.attachment.anchorPoint];
[path addLineToPoint:self.imageView.center];
BackgroundView *bgView = (BackgroundView *)self.view;
bgView.path = path;
path.lineWidth = 5;
[bgView setNeedsDisplay];
};
[self.animator addBehavior:self.attachment];
}
谢谢大家!