CABasicAnimation 给layer改变颜色不起作用的原因

是因为对应的view bgcolor为白色

所以不起作用

去掉背景色设置就好了


还有boardercolor不起作用的另一个原因是


   

  CABasicAnimation* selectionAnimation = [CABasicAnimation

                                            animationWithKeyPath:@"borderColor"];

    selectionAnimation.duration = 1;

    selectionAnimation.toValue = (id)[UIColor colorWithIntegerValue:dialog_textfield_gray alpha:1].CGColor; //一定要设置fromValue

    

    selectionAnimation.fromValue = (id)[UIColor colorWithIntegerValue:pinterest_red alpha:1].CGColor;

    selectionAnimation.removedOnCompletion = NO;

    [self.layer setBorderColor: (id)[UIColor colorWithIntegerValue:dialog_textfield_gray alpha:1].CGColor];//因为这里会直接设置target颜色 如果fromvalue不设置就看不到效果了

    [self.layer addAnimation:selectionAnimation

                      forKey:@"borderColor"];

forkey也需要设置同样的



下面的转在于

http://blog.sina.com.cn/s/blog_76264a170101fdcv.html

    Apple的官方文档里有提到,CABasicAnimation的delegate是少数会retain的delegate之一。网上介绍Core Animation的资料里基本也都会强调这一点。

    delegate会被animation对象retain,就有可能出现retain cycle。道理谁都懂,但是实践起来一不小心,retain cycle就在不知不觉中上了你的身。

    比如如下CABasicAnimation代码:

CABasicAnimation  * anim  =  [ CABasicAnimation  animationWithKeyPath: @"position" ];
anim . duration  =  1.0f;
anim . fromValue  =  [ NSValue  numberWithCGPoint: someView . center ];
anim . toValue  =  [ NSValue  numberWithCGPoint: anotherPoint ];

[ someView . layer  addAnimation: anim  forKey: @"anim" ];

    很简单的一个1.0s内将someView从原位移到anotherPoint的动画。

    放心,这个动画连delegate都没有,肯定不会有retain cycle的。

    这个动画很多时候不能满足我们的要求,原因是当动画结束以后,someView又回到原位去了,大多时候,我们希望的是someView留在anotherPoint的位置。

    这时我们有两种解决方案:

    方案一是利用anim的removeOnCompletion属性:

anim . removeOnCompletion  =  NO;

    这个属性是顾名思义的。设置成NO了以后,动画在结束后不会被移除,结合autoReverse属性,就能做到停留在最终位置。

    方案二是在动画加到layer上之后,人工设置view到最终位置:

[ someView  setCenter: anotherPoint ];

    这两种方案相比,孰优孰劣呢?

    似乎在直觉上,第二种方案的代码看起来更丑一点,因为如果你简单了解一点Core Animation的话,你会发现,那段动画实际上是在setCenter之后才执行的,只是你看不出来而已。既然CA给我们提供了removeOnCompletion的属性,我们为什么不用呢?

    似乎扯远了,迄今为止,delegate还未出现,但是已经隐约露出了一点端倪。

    如果我们给这段动画设置了anim.delegate = self;同时又用方案一实现了动画结束后不移除……于是……

self持有someView,someView持有someView.layer,someView.layer持有anim,anim再持有self的话……

    终于,一个retain cycle就这样悄悄地产生了。因为anim不会在动画结束时被移除,所以这个retain cycle不会被打破,尤其是在ARC下,想人工break都不容易。

    假如这个动画是循环的或者autoReverse的,它会一直在动,这种情况下相信所有的程序员都会注意到并且提醒自己,丫还没有被释放。但是如果是上面那种情况,估计相当一部分人就会忘了这里还有一个已经停了的动画的事情了。

    所以我建议,在有delegate存在的情况下,尽量还是不要用方案一来解决问题了。

    那么方案二那么丑怎么办呢……

    其实,这种情况,如果能用UIView动画实现,为啥还要用CA呢?

[ UIView  beginAnimations: @"anim"  context: nil ];
...  动画设置
[ someView  setCenter: anotherPoint ];
[ UIView  commitAnimation ];

    UIView的动画完成之后,属性就维持在目标状态了。

    如果UIView动画实在不能满足要求,丑就丑吧……


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值