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];
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM