如何为自定义视图选择设置膨胀和颜色更改动画?

时间:2014-12-12 22:51:18

标签: ios objective-c uiview core-animation

我有自定义UIView对象的层次结构。叶子视图是可选择的。他们有isSelected属性。当此设置为YES时,我想要的效果是视图立即更改为“选定”颜色,然后暂时膨胀,然后返回其原始大小。我想到以下代码可以解决这个问题:

self.backgroundColor = [UIColor colorWithRed: 0 green: 0.5 blue: 1 alpha: 1];
CGRect currentFrame = self.frame;
CGRect bigFrame = CGRectInset(currentFrame, -50, -50);
[UIView animateWithDuration: 0.4 animations:^{
    self.frame = bigFrame;
} completion:^(BOOL finished) {
    if (finished ) {
        [UIView animateWithDuration: 0.4 animations:^{
            self.frame = currentFrame;
        }];
    }
}];

我在这里夸大了时间和位移,因为我试图看看究竟发生了什么。会发生什么,颜色变化似乎是动画的,所以它会从默认的0.93白色变为我的蓝色。此外,它的大小不会增长。它似乎只是通过插入量向下和向右平移,然后返回正常点(而不是向所有方向增长)。

我错过了什么?

2 个答案:

答案 0 :(得分:1)

使用关键帧动画:

CAKeyframeAnimation *bounceAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
// 200 is example side of the big view, but you can apply any formula to it. For example relative to superview, or screen bounds
CGFloat multiplier = 200 / MAX(self.frame.size.height, self.frame.size.width)
bounceAnimation.values =
@[@(1 - 0.1 * multiplier, 
  @(1 + 0.3 * multiplier), 
  @(1 + 0.1 * multiplier,
  @1.0];
bounceAnimation.duration = 0.25;
bounceAnimation.removedOnCompletion = YES;
bounceAnimation.fillMode = kCAFillModeForwards;
[self.layer addAnimation:bounceAnimation forKey:@"bounceAnimation"];

答案 1 :(得分:0)

简单CGAffineTransformMakeScale怎么样?像这样......

[UIView animateWithDuration: 0.4 animations:^{
    // Update 1.3 to what ever works for you
    self.transform = CGAffineTransformMakeScale(1.3, 1.3);
} completion:^(BOOL finished) {
    if (finished ) {
        [UIView animateWithDuration: 0.4 animations:^{
            self.transform = CGAffineTransformMakeScale(1.0, 1.0);
        }];
    }
}];

https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGAffineTransform/#//apple_ref/c/func/CGAffineTransformMakeScale