2

我有 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方法。

4

4 回答 4

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];
}
于 2013-08-01T09:29:08.110 回答
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];
        });
    });
}

如果你看动画更慢然后增加持续时间。

于 2013-08-01T09:18:25.167 回答
0

您正在使用正确的功能,但只有您必须提及图像名称。

- (void)updateViewBackground  {
    int randomNumber = arc4random_uniform(10);
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:[NSString stringWithFormat:@"random_bg_%i.png",randomNumber]]];
}
于 2013-08-01T09:46:03.663 回答
0

要停止图像突然变化,您需要为变化设置动画,这-[UIView animateWithDuration: animations:]就是您要寻找的。这是一个小代码示例:

self.view.backgroundColor = [UIColor redColor];

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

显然,您需要对其进行编辑以适合您的代码等。希望它有所帮助!

编辑:这是类参考的链接,以防您想阅读它!

于 2013-08-08T09:30:10.727 回答