iOS rainbow colors array

前端 未结 3 930
忘掉有多难
忘掉有多难 2021-01-02 05:49

I am setting up an array that has a transition throughout he colors of the rainbow. Right now I\'ve just manually entered the colors in the array but there are too many to m

相关标签:
3条回答
  • 2021-01-02 06:27

    Far simpler, use -[UIColor colorWithHue:saturation:brightness:alpha:], like so:

    NSMutableArray *colors = [NSMutableArray array];
    
    float INCREMENT = 0.05;
    for (float hue = 0.0; hue < 1.0; hue += INCREMENT) {
        UIColor *color = [UIColor colorWithHue:hue
                                    saturation:1.0
                                    brightness:1.0
                                         alpha:1.0];
        [colors addObject:color];
    }
    

    This allows you to vary the hue (or color) without changing how bright the color is on the screen, which you're very likely not preserving right now. It's also far simpler to write, and far clearer to a later reader.

    0 讨论(0)
  • 2021-01-02 06:38

    A Swift 5, iOS 13 update to BJHomer answer

    extension UIButton {
      func rainbowText() {
        var colors:[UIColor] = []
        let increment:CGFloat = 0.02
        for hue:CGFloat in stride(from: 0.0, to: 1.0, by: increment) {
          let color = UIColor(hue: hue, saturation: 1.0, brightness: 1.0, alpha: 1.0)
          colors.append(color)
        }
        var colorIndex = 0
        Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { (timer) in
          if colorIndex < colors.count {
            self.setTitleColor(colors[colorIndex], for: .normal)
            colorIndex = colorIndex + 1
          } else {
            self.setTitleColor(colors[0], for: .normal)
            timer.invalidate()
          }
        }
      }
    }
    

    You call it like this ...

    buttonOutlet.rainbowText()
    
    0 讨论(0)
  • 2021-01-02 06:45

    3 nested for loops and 3 variables r, g, b, and add 0.25 each time the loop occurs.

    0 讨论(0)
提交回复
热议问题