簡體   English   中英

從WhiteColor到RedColor的UIButton背景顏色動畫

[英]Animate Background Color Of UIButton from WhiteColor to RedColor

我正在嘗試制作一種顏色脈沖效果來動畫UIButton背景顏色,使其從顏色(WhiteColor)連續變化到另一種顏色(RedColor)。 我正在嘗試使用CABasicAnimation來改變Opacity,但我也無法使用顏色。

    CABasicAnimation *theAnimation;

    theAnimation=[CABasicAnimation animationWithKeyPath:@"opacity"];
    theAnimation.duration=1.0;
    theAnimation.repeatCount=HUGE_VALF;
    theAnimation.autoreverses=YES;
    theAnimation.fromValue=[NSNumber numberWithFloat:1.0];
    theAnimation.toValue=[NSNumber numberWithFloat:0.0];
    [BigButton.layer addAnimation:theAnimation forKey:@"animateOpacity"];

我們將不勝感激。 謝謝

我找到了正確的方法。 你需要記住CGColor。 這是我的錯。 編譯器在這里沒有幫助。

目標C.

CABasicAnimation *theAnimation=[CABasicAnimation animationWithKeyPath:@"backgroundColor"];
theAnimation.duration=1.0;
theAnimation.repeatCount=HUGE_VALF;
theAnimation.autoreverses=YES;
theAnimation.fromValue= [[UIColor redColor] CGColor];
theAnimation.toValue= [[UIColor blueColor] CGColor];
[BigButton.layer addAnimation:theAnimation forKey:@"ColorPulse"];

迅速

let colorAnimation = CABasicAnimation(keyPath: "backgroundColor")
colorAnimation.fromValue = UIColor.redColor().CGColor
colorAnimation.toValue = UIColor.blueColor().CGColor
colorAnimation.duration = 1
colorAnimation.autoreverses = true
colorAnimation.repeatCount = FLT_MAX
self.layer.addAnimation(colorAnimation, forKey: "ColorPulse")

我終於找到了解決方案:我制作了一個兩幀動畫,其中我首先將背景顏色更改為紅色,而在第二幀中我將其變為白色。 我也可以操縱相對持續時間

    [UIView animateKeyframesWithDuration:2.0 delay:0.0 options:UIViewKeyframeAnimationOptionAutoreverse | UIViewKeyframeAnimationOptionRepeat animations:^{
        [UIView addKeyframeWithRelativeStartTime:0.0 relativeDuration:0.5 animations:^{
            someView.backgroundColor = [UIColor redColor];
        }];
        [UIView addKeyframeWithRelativeStartTime:0.5 relativeDuration:0.5 animations:^{
            someView.backgroundColor = [UIColor whiteColor];
        }];
    } completion:nil];

Swift 4 - 對按鈕上的任何更改進行動畫處理( backgroundColortitletitleColor ):

UIView.transition(with: yourButton, duration: 0.3, options: .curveEaseInOut, animations: {
  self.yourButton.backgroundColor = UIColor.red
  self.yourButton.setTitle("new title", for: .normal)
  self.yourButton.setTitleColor(.white, for: .normal)
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM