iOS - Smooth Color Change Transition/Animation

前端 未结 3 690
不知归路
不知归路 2021-02-07 01:47

I want to have a smooth color transition that goes across the entire spectrum (i.e. red, blue, green, yellow, orange, etc.)

Also want to be able to have smooth transitio

3条回答
  •  温柔的废话
    2021-02-07 02:25

    One possible way of doing it is apply background color animation on view's layer.

    Now to pass through entire spectrum you have to work on combinations of three colors.

    The best way to achieve this is to use 'Hue'.

    [[UIColor alloc] initWithHue:135/360.0f saturation:1 brightness:1 alpha:1]

    Now you have to iterate for all Hue values and you will get the smooth transition that goes across all the spectrum.

    Sample code:

    1. make a local variable

    int _currentColorHue = 0;

    1. recursive call for change background color.

    -(void)animateMyView {

    [UIView animateWithDuration:0.01 animations:^{
        self.view.layer.backgroundColor = [[UIColor alloc] initWithHue:_currentColorHue/360.0f saturation:1 brightness:1 alpha:1].CGColor;
    } completion:^(BOOL finished)
    {
        _currentColorHue++;
        if (_currentColorHue > 360)
        {
            _currentColorHue = 0;
        }
        [self animateMyView];
    }];
    }
    

    You can stop the animation according to your use.

提交回复
热议问题