Iphone 如何平滑地更改视图的背景色
我有10个图像,我需要的背景颜色随机改变,每4秒与平滑动画 我的代码是Iphone 如何平滑地更改视图的背景色,iphone,ios,ios6,Iphone,Ios,Ios6,我有10个图像,我需要的背景颜色随机改变,每4秒与平滑动画 我的代码是 self.bgTimer = [NSTimer scheduledTimerWithTimeInterval: 4.0 target: self selector: @selector(updateViewBackground) userInfo: nil repeats: YES]; self.bgTimer是一个NSTim
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 {
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 {
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);
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];
}];
显然,您需要编辑此文件以适合您的代码,等等。希望它有帮助
编辑:这是课堂参考,以防你想了解它 对不起,但是我已经试过了,但它不起作用。查看我更新的答案。它只适用于重复:不适用于第一次,因为计时器只运行一次,但适用于重复:是的,它不起作用。我现在尝试它,适用于慢速动画,只是增加了答案中给出的持续时间。谢谢你更新的答案起作用。它工作正常,但阻止了我的主要任务线程,它上面有一个UITable,它没有被正确地滚动,有时甚至没有被滚动,我们可以用其他方式来做吗…然后将它添加到全局队列中。