prosource

UI 레이블의 배경색을 애니메이션화하는 방법은?

probook 2023. 9. 25. 22:50
반응형

UI 레이블의 배경색을 애니메이션화하는 방법은?

이게 잘 될 것 같은데, 안 돼요.색상이 한번에 초록색으로 바뀝니다.

self.labelCorrection.backgroundColor = [UIColor whiteColor];
[UIView animateWithDuration:2.0 animations:^{
    self.labelCorrection.backgroundColor = [UIColor greenColor];
}];

어디에서도 문서화된 것을 찾을 수는 없지만, 그 안에backgroundColor의 소유물.UILabel당신의 코드가 바닐라와 함께 잘 작동하기 때문에 애니메이션이 되지 않습니다.UIView. 그러나 레이블 보기 자체의 배경색을 설정하지 않는 한 이 해킹이 작동하는 것으로 보입니다.

#import <QuartzCore/QuartzCore.h>

...

theLabel.layer.backgroundColor = [UIColor whiteColor].CGColor;

[UIView animateWithDuration:2.0 animations:^{
    theLabel.layer.backgroundColor = [UIColor greenColor].CGColor;
} completion:NULL];

스위프트

  1. (중요) UILabel의 배경색을 클리어(IB 또는 코드)로 설정합니다.예를 들어,

    override func viewDidLoad() {
        super.viewDidLoad()
    
        myLabel.backgroundColor = UIColor.clear
    }
    
  2. 레이어 배경색을 애니메이션화합니다.

    @IBAction func animateButtonTapped(sender: UIButton) {
    
        UIView.animate(withDuration: 1.0, animations: {
            self.myLabel.layer.backgroundColor = UIColor.red.cgColor
        })
    }
    

참고하세요CGColor다음에 추가됩니다.UIColor.

결과

enter image description here

스위프트 3

레이블 배경색을 흰색에서 녹색으로 애니메이션화하려면 다음과 같이 레이블을 설정합니다.

self.labelCorrection.backgroundColor = UIColor.clear
self.labelCorrection.layer.backgroundColor = UIColor.white.cgColor

다음과 같이 애니메이션을 만듭니다.

UIView.animate(withDuration: 2.0) { 
    self.labelCorrection.layer.backgroundColor = UIColor.green.cgColor
}

다시 애니메이션을 만들 수 있도록 원래 상태로 돌아가려면 애니메이션을 제거해야 합니다.

self.labelCorrection.layer.backgroundColor = UIColor.white.cgColor
self.labelCorrection.layer.removeAllAnimations()

애니메이션을 만들 수는 있지만, 어떤 이유에서인지 색상을 지우기 위해 먼저 (프로그래밍 방식으로) 설정해야 했습니다.그것이 없으면 애니메이션이 작동하지 않거나 보이지 않습니다.

사용자 정의 테이블 셀에 UI 라벨의 배경색을 애니메이션으로 만들고 있습니다.다음은 willDisplayCell 메서드의 코드입니다.셀포로우에 애니메이션을 설정하려고 하지는 않을 것입니다. 테이블 옆에 배치된 많은 부분이 얼룩져 있기 때문입니다.

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
        ((RouteListCell *)cell).name.backgroundColor = [UIColor clearColor];
        [((RouteListCell *)cell).name backgroundGlowAnimationFromColor:[UIColor whiteColor] toColor:[UIColor redColor] clearAnimationsFirst:YES];
}

제 애니메이션 루틴은 다음과 같습니다.

-(void) backgroundGlowAnimationFromColor:(UIColor *)startColor toColor:(UIColor *)destColor clearAnimationsFirst:(BOOL)reset;
{
    if (reset)
    {
        [self.layer removeAllAnimations];
    }

    CABasicAnimation *anAnimation = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
    anAnimation.duration = 1.00;
    anAnimation.repeatCount = HUGE_VAL;
    anAnimation.autoreverses = YES;
    anAnimation.fromValue = (id) startColor.CGColor; // [NSNumber numberWithFloat:1.0];
    anAnimation.toValue = (id) destColor.CGColor; //[NSNumber numberWithFloat:0.10];
    [self.layer addAnimation:anAnimation forKey:@"backgroundColor"];
}

NSTimer 또는 CAD 디스플레이 링크 콜백을 기준으로 컬러 애니메이션을 수동으로 수행합니다(예: 20fps).전체 애니메이션 시간(예시 2.0초) 동안의 부분 경과 시간을 기준으로 RGB 또는 HSV로 자신의 색상 변화 곡선을 계산하거나 40개의 중간 색상 배열을 사용해야 합니다.

이거 한번 해보세요.

[UIView transitionWithView:yourView duration:0.2 options:UIViewAnimationOptionTransitionNone animations:^{

[yourView setBackgroundColor:[UIColor colorWithRed:0.8588 green:0.8588 blue:0.8588 alpha:1]];
    }completion:^(BOOL finished) {

 }];

저한테는 효과가 있어요.

저는 최근에 이 문제를 다시 한 번 접했고 몇 가지 연구 끝에 기본적으로 아무것도 변하지 않았다고 생각했습니다(아마도 예측 가능한 미래에는 변하지 않을 것입니다). 그래서 결국 페이스북 POP 프레임워크(뿐만 아니라)를 사용하게 되었습니다.

보기와 레이어 모두에서 기본 속성의 애니메이션을 쉽게 수행할 수 있지만, 추가적인 코딩을 통해 색상 간의 원활한 전환(기본적으로 원하는 것은 무엇이든, 사용자 지정 유형까지도)을 제공합니다.따라서 배경색의 경우 다음과 같은 작업을 수행합니다.

   // Create spring animation (there are more types, if you want)
   let animation = POPSpringAnimation(propertyNamed: kPOPViewBackgroundColor)

   // Configure it properly
   animation.autoreverses = false
   animation.removedOnCompletion = true
   animation.fromValue = UIColor.yourBeginningColor()
   animation.toValue = UIColor.yourFinalColor()

   // Add new animation to your view - animation key can be whatever you like, serves as reference
   label.pop_addAnimation(animation, forKey: "YourAnimationKey")

비올라, 이제 그 성질을 가진 모든 것의 배경색을 애니메이션으로 만들 수 있습니다!

Swift 4.1 UILabel 확장:

이 확장자를 코드에 추가합니다.

extension UILabel {

    /** Animates the background color of a UILabel to a new color. */
    func animateBackgroundColor(to color : UIColor?, withDuration : TimeInterval, completion : ((Bool) -> Void)? = nil) {
        guard let newColor = color else { return }
        self.backgroundColor = .clear
        UIView.animate(withDuration: withDuration, animations: {
            self.layer.backgroundColor = newColor.cgColor
        }, completion: completion)
    }

}

다음과 같이 사용해야 합니다.

myUILabel.animateBackgroundColor(to: .red, withDuration: 0.5)

이제 원래 색을 복원하려면 다음과 같이 사용합니다.

// Storing the orignal color:
let originalColor = myUILabel.backgroundColor

// Changing the background color:
myUILabel.animateBackgroundColor(to: .red, withDuration: 0.5)

// ... Later:

// Restoring the original color:
myUILabel.animateBackgroundColor(to: originalColor, withDuration: 0.5, completion: {
    (value: Bool) in
    myUILabel.backgroundColor = originalColor
})

배경색은 애니메이션이라고 문서에 나와 있습니다.

http://developer.apple.com/library/ios/ #문서/uikit/참조/UI뷰_클래스/UI뷰/UI뷰.html#/apple_ref/doc/uid/TP40006816-CH3-SW131

언제부터인지는 잘 모르겠습니다.

Quartz에 빠져들고 싶지 않다면, 사전 답변 중 하나에 따라 UILabel과 같은 크기의 빈 UIView를 생성하고 UILabel과 같은 위치에 배치하면(그리고 Z 순서로, 그 아래) 해당 UIView의 배경색을 애니메이션화할 수 있습니다(이것을 시도해 보았고, 나에게 적합합니다).

다음은 참조 사항입니다.

animations 뷰에 커밋할 변경 내용이 들어 있는 블록 개체입니다.여기서 보기 계층에서 보기의 애니메이션 속성을 프로그래밍 방식으로 변경할 수 있습니다.이 블록은 매개 변수를 사용하지 않으며 반환 값도 없습니다.이 매개 변수는 NULL이 아니어야 합니다.

제가 알기로는 뷰가 애니메이션 블록을 호출하면 뷰 레이블 배경색이 그 이후로 초록색으로 커밋됩니다.그러면 라벨 배경색을 다른 색으로 변경하지 않으면 항상 녹색으로 표시됩니다.이렇게 생각합니다.

언급URL : https://stackoverflow.com/questions/3762561/how-to-animate-the-background-color-of-a-uilabel

반응형