我正在设置一个数组,该数组在整个彩虹色之间都有过渡。现在我只是在数组中手动输入了颜色,但是手动输入的颜色太多了……到目前为止,我只是从0.25到0.5到0.75到1等等,直到从红色变成绿色再变成蓝色为止然后回来。 (请参阅下面的代码)我如何让数组自动生成超过0.25-> 0.5-> 0.75但可能是0.05-> 0.10-> 0.15-> 0.20等的颜色,依此类推,...这是我的数组:
rainbowColors = [[NSArray alloc] initWithObjects:
[UIColor colorWithRed:1 green:0 blue:0 alpha:1],
[UIColor colorWithRed:1 green:0.25 blue:0 alpha:1],
[UIColor colorWithRed:1 green:0.5 blue:0 alpha:1],
[UIColor colorWithRed:1 green:0.75 blue:0 alpha:1],
[UIColor colorWithRed:1 green:1 blue:0 alpha:1],
[UIColor colorWithRed:0.75 green:1 blue:0 alpha:1],
[UIColor colorWithRed:0.5 green:1 blue:0 alpha:1],
[UIColor colorWithRed:0.25 green:1 blue:0 alpha:1],
[UIColor colorWithRed:0 green:1 blue:0 alpha:1],
[UIColor colorWithRed:0 green:1 blue:0.25 alpha:1],
[UIColor colorWithRed:0 green:1 blue:0.5 alpha:1],
[UIColor colorWithRed:0 green:1 blue:0.75 alpha:1],
[UIColor colorWithRed:0 green:1 blue:1 alpha:1],
[UIColor colorWithRed:0 green:0.75 blue:1 alpha:1],
[UIColor colorWithRed:0 green:0.5 blue:1 alpha:1],
[UIColor colorWithRed:0 green:0.25 blue:1 alpha:1],
[UIColor colorWithRed:0 green:0 blue:1 alpha:1],
[UIColor colorWithRed:0.25 green:0 blue:1 alpha:1],
[UIColor colorWithRed:0.5 green:0 blue:1 alpha:1],
[UIColor colorWithRed:0.75 green:0 blue:1 alpha:1],
[UIColor colorWithRed:1 green:0 blue:1 alpha:1],
[UIColor colorWithRed:1 green:0 blue:0.75 alpha:1],
[UIColor colorWithRed:1 green:0 blue:0.5 alpha:1],
[UIColor colorWithRed:1 green:0 blue:0.25 alpha:1],nil];
更简单,使用-[UIColor colorWithHue:saturation:brightness:alpha:]
,如下所示:
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];
}
这可以让您改变色调(或颜色),而无需更改屏幕上颜色的明亮程度,您现在很可能无法保留这种颜色。编写起来也容易得多,对以后的读者也更清楚。
3个嵌套的循环和3个变量r,g,b,每次循环发生时加0.25。
[Swift 5,iOS 13更新为BJHomer答案
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()
}
}
}
}
您这样称呼它...
buttonOutlet.rainbowText()