[英]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.