动画UIView的框架和角半径一起动画

时间:2014-11-06 00:32:41

标签: ios animation uiview

所以我试图用UIView制作一个缩小/增长的圈子。我正在使用UIView.animateWithDuration ...(blah blah blah)用于视图的框架,而CABasicAnimation用于为视图的(图层)角半径设置动画。两者都以正确的圆周值(圆角半径= 1/2宽度)设置正确持续时间和结束的动画。问题是在动画期间,CABasicAnimation和UIView.animateWithDuration似乎有不同的动画曲线。如何实现正确的圆形动画。

如果答案是对农场膨胀使用CABAsicAnimation,请解释 如何做到这一点。

谢谢!


代码:

此代码位于UIView的扩展名中。

//This is how it's being used to shrink the circle:

circleview.growByPixles(-10, seconds: 0.3, completion: {})
circleview.setCornerRadius(radius:(circleview.bounds.size.width - 10) / 2 seconds: 0.3)

//////

func morphToFrame(frame: CGRect, seconds: Double, completion: () -> ()) {
    UIView.animateWithDuration(seconds,
        animations: {
            self.frame = frame
        },
        completion: { _ in
            completion()
        })
}

//negative integers shrink
func growByPixels(pixels: CGFloat, seconds: Double, completion: () -> ()) {
    var f:CGRect = self.frame

    var newFrame:CGRect = CGRect(x: f.origin.x - pixels/2, y: f.origin.y - pixels/2,  width: f.size.width + pixels, height: f.size.height + pixels)

    self.morphToFrame(newFrame, seconds: seconds, completion: completion)
}

func setCornerRadius(radius: CGFloat, seconds: Double) {

    self.layer.masksToBounds = true

    var animation = CABasicAnimation(keyPath: "cornerRadius")
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
    animation.fromValue = NSNumber(float: Float(self.layer.cornerRadius))
    self.layer.cornerRadius = radius
    animation.duration = seconds
    self.layer.addAnimation(animation, forKey: "cornerRadius")
}

1 个答案:

答案 0 :(得分:6)

我像这样调整我的圈子视图:

- (void)resizeCircleView:(CGRect)frame {

    CGRect estimateFrame = frame;
    float duration = 1.0f;

    [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        [circle setFrame:estimateFrame];
    } completion:nil];

    CGFloat estimateCorner = estimateFrame.size.width / 2;
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"cornerRadius"];
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    animation.fromValue = @(circle.layer.cornerRadius);
    animation.toValue = @(estimateCorner);
    animation.duration = duration;
    [circle.layer setCornerRadius:estimateCorner];
    [circle.layer addAnimation:animation forKey:@"cornerRadius"];
}