[英]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.bgTimer
是NSTimer
屬性。
改變背景的方法是
- (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]]];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.