繁体   English   中英

如何平滑更改视图的背景色

[英]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.bgTimerNSTimer属性。

改变背景的方法是

- (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]]];
}

要停止图像的突然更改,您需要为更改添加动画效果-[UIView animateWithDuration: animations:]是您要的内容。 这是一个小代码示例:

self.view.backgroundColor = [UIColor redColor];

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

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

编辑:这是指向类引用的链接 ,以防您要阅读有关它的信息!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM