21

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 transitions of colors in specific spectrum (i.e. all reds).

Are there any simple algorithms/recursive functions/formulas that can help simplify this process?

3 Answers 3

61

One very simple way to accomplish this would be to use a UIView animation block.

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

This will interpolate between whatever view's previous background color was, and red over the course of 1 second.

Swift:

UIView.animate(withDuration: 1.0) { 
    view.backgroundColor = .red
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. That is helpful, but I actually need an algorithm as I have to send the color codes individually to a device. Can't just use a UIView's methods...
This is awesome.
4

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.

Comments

3

Use following code for color transition in iOS, it gives you various configureable options:
1) Delay before starting animation
2) Callback on animation completion
3) Options for animation

[UIView animateWithDuration:1.0 delay:0.2 options:0 animations:^{
        view.backgroundColor = [UIColor greenColor];
    } completion:^(BOOL finished)
     {
         NSLog(@"Color transformation Completed");
     }];

For Detailed description of different animations please visit:
UIView Tutorial for iOS: How To Use UIView Animation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.