iOS动画实现:弹簧效果

源码地址: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];
}
复制代码

 

posted @   shangdahao  阅读(11955)  评论(4编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示