簡體   English   中英

如何平滑更改視圖的背景色

[英]How to change background color of view smoothly

我有10張圖像,我需要每4秒隨機更改背景顏色並進行平滑的動畫處理。

我的代碼是

self.bgTimer = [NSTimer scheduledTimerWithTimeInterval: 4.0 target: self
                        selector: @selector(updateViewBackground)
                        userInfo: nil repeats: YES]; 

self.bgTimerNSTimer屬性。

改變背景的方法是

- (void)updateViewBackground {
int randomNumber = arc4random_uniform(10);
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:[NSString stringWithFormat:@"random_bg_%i",randomNumber]]];
}

它會根據所選的隨機圖像更改背景,但會突然更改背景。

我需要平滑地更改顏色(更改過程需要2秒鍾,例如淡入淡出或交叉溶解)。

如何做到這一點。

還有一種更好的方法代替此NSTimer方法。

嘗試與此。

- (void)updateViewBackground {
    CATransition *animation = [CATransition animation];
    [animation setDelegate:self];
    [animation setType:kCATransitionFromBottom];
    [animation setDuration:1.0];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [[self.view layer] addAnimation:animation forKey:@"transitionViewAnimation"];
    int randomNumber = arc4random_uniform(10);
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:[NSString stringWithFormat:@"random_bg_%i",randomNumber]]];
}

要么

- (void)updateViewBackground {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.3];
        int randomNumber = arc4random_uniform(10);
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:[NSString stringWithFormat:@"random_bg_%i",randomNumber]]];
        [UIView commitAnimations];
}

如果您希望通過動畫來更改顏色,請嘗試此操作。

    - (void)updateViewBackground {
    int randomNumber = arc4random_uniform(10);
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,  0ul);
    dispatch_async(queue, ^{
        dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            [UIView transitionWithView:self.view duration:7.25 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
                self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:[NSString stringWithFormat:@"random_bg_%i",randomNumber]]];
            } completion:nil];
        });
    });
}

如果您看動畫較慢,則增加持續時間。

您正在使用正確的功能,但僅需提及圖像名稱。

- (void)updateViewBackground  {
    int randomNumber = arc4random_uniform(10);
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:[NSString stringWithFormat:@"random_bg_%i.png",randomNumber]]];
}

要停止圖像的突然更改,您需要為更改添加動畫效果-[UIView animateWithDuration: animations:]是您要的內容。 這是一個小代碼示例:

self.view.backgroundColor = [UIColor redColor];

[UIView animateWithDuration:1.0 animations ^{
    self.view.backgroundColor = [UIColor greenColor];
}];

顯然,您需要對其進行編輯以適合您的代碼,等等。希望對您有所幫助!

編輯:這是指向類引用的鏈接 ,以防您要閱讀有關它的信息!

暫無
暫無

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

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