我有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
方法。
答案 0 :(得分:1)
试试这个......
- (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];
}
答案 1 :(得分:0)
如果您希望使用类似动画来更改颜色,请尝试此操作。
- (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];
});
});
}
如果你看动画更慢,那就增加持续时间。
答案 2 :(得分:0)
您正在使用正确的功能,但只需提及图像名称。
- (void)updateViewBackground {
int randomNumber = arc4random_uniform(10);
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:[NSString stringWithFormat:@"random_bg_%i.png",randomNumber]]];
}
答案 3 :(得分:0)
要停止图像突然改变,您需要为更改设置动画-[UIView animateWithDuration: animations:]
正是您正在寻找的。这是一个小代码示例:
self.view.backgroundColor = [UIColor redColor];
[UIView animateWithDuration:1.0 animations ^{
self.view.backgroundColor = [UIColor greenColor];
}];
显然你需要编辑它以适合你的代码等。希望它有所帮助!
编辑:如果你想阅读它,请参阅课程参考a link!