iOS动画实现:弹簧效果

iOS视图弹簧效果实现
原帖地址:http://www.cnblogs.com/shangdahao/archive/2013/06/04/3116731.html

源码地址:https://github.com/thermogl/TISpringLoadedViews,


这个比较复杂,我写了个简化版的:


https://www.dropbox.com/s/sv3yhm8dovh0adq/SpringDemo.zip



- (void)simulateSpringWithDisplayLink:(CADisplayLink *)displayLink {

if (springEnabled && !self.panning){
CGPoint displacement
= CGPointMake(self.center.x - restCenter.x,
self.center.y
- restCenter.y);
//控件收到的力
CGPoint kx = CGPointMake(springConstant * displacement.x, springConstant * displacement.y);
//控件受到的阻力
CGPoint bv = CGPointMake(dampingCoefficient * velocity.x, dampingCoefficient * velocity.y);
//加速度
CGPoint acceleration = CGPointMake((kx.x + bv.x) / mass, (kx.y + bv.y) / mass);

velocity.x
-= (acceleration.x * displayLink.duration);
velocity.y
-= (acceleration.y * displayLink.duration);

//设置控件新位置
CGPoint newCenter = self.center;
newCenter.x
+= (velocity.x * displayLink.duration);
newCenter.y
+= (velocity.y * displayLink.duration);
[self setCenter:newCenter];
}
}


这个方法由CADisplayLink负责调用,每秒钟默认60次。要看懂这段代码,首先你要了解弹簧的原理,比如拉起弹簧收到的力怎么计算,往回弹收到的阻力怎么计算。


 


下面是手势操作的代码,也就是拖动时触发的方法:



- (void)viewWasPanned:(UIPanGestureRecognizer *)sender {

CGPoint translation
= CGPointApplyAffineTransform([sender translationInView:self.superview], CGAffineTransformMakeScale(panDragCoefficient, panDragCoefficient));
CGPoint translatedCenter
= CGPointMake(self.center.x + translation.x, self.center.y + translation.y);

if (translation.x > 0 && (translatedCenter.x - restCenter.x) > panDistanceLimits.right){
translation.x
-= (translatedCenter.x - restCenter.x) - panDistanceLimits.right;
}
else if (translation.x < 0 && (restCenter.x - translatedCenter.x) > panDistanceLimits.left){
translation.x
+= (restCenter.x - translatedCenter.x) - panDistanceLimits.left;
}

if (translation.y > 0 && (translatedCenter.y - restCenter.y) > panDistanceLimits.bottom){
translation.y
-= (translatedCenter.y - restCenter.y) - panDistanceLimits.bottom;
}
else if (translation.y < 0 && (restCenter.y - translatedCenter.y) > panDistanceLimits.top){
translation.y
+= (restCenter.y - translatedCenter.y) - panDistanceLimits.top;
}

[self setCenter:CGPointMake(self.center.x
+ translation.x, self.center.y + translation.y)];
[sender setTranslation:CGPointZero inView:self.superview];
}


 

本文链接

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值