OGeek|极客世界-中国程序员成长平台

标题: iphone - 如何平滑更改 View 的背景颜色 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 13:14
标题: iphone - 如何平滑更改 View 的背景颜色

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



Best Answer-推荐答案


用这个试试..

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

关于iphone - 如何平滑更改 View 的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17989849/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4