【iOS】⽤RGB颜⾊模型实现彩虹渐变粗略的在⽹上搜索了⼀下没有到现成答案,就⾃⼰动⼿实现了⼀下。
实现思路:
先在⽹上查到⾚橙黄绿青蓝紫的rgb值,观察规律,然后⽤循环实现。
⾚ (255,0,0)
橙 (255,165,0)
黄 (255,255,0)
绿 (0,255,0)
青 (0,127,255)
蓝 (0,0,255)
紫 (139,0.255)
下⾯⽤OC实现⼀个创建彩虹渐变颜⾊数组的⽅法。
核⼼代码如下:
- (void)initRainbowColors{
_rainbowColors = [[NSMutableArray alloc]init];
int red = 255;
int green = 0;
int blue = 0;
//⾚-橙-黄
while (green < 256) {
UIColor *rColor = [[UIColor alloc]initWithRed:red / 255.0 green:green  /255.0 blue:blue /255.0 alpha:1.0];
[_rainbowColors addObject:rColor];
green += COLOR;
}
//黄-绿
while (red > 0) {
red -= COLOR;
UIColor *rColor = [[UIColor alloc]initWithRed:red / 255.0 green:green  /255.0 blue:blue /255.0 alpha:1.0];
[_rainbowColors addObject:rColor];
}
//绿 - 蓝
while (green > 0) {
green -= COLOR;
渐变颜代码大全blue += COLOR;
UIColor *rColor = [[UIColor alloc]initWithRed:red / 255.0 green:green  /255.0 blue:blue /255.0 alpha:1.0];
[_rainbowColors addObject:rColor];
}
//蓝-紫
while (red < 255) {
red += COLOR;
UIColor *rColor = [[UIColor alloc]initWithRed:red / 255.0 green:green  /255.0 blue:blue /255.0 alpha:1.0];
[_rainbowColors addObject:rColor];
}
}
细⼼的朋友可以看到 “青” 被放弃了,这是为了算法实现上更简洁清晰些。
实践表明这样做最终效果也能可以接受(见效果图)
如果⼀定要按照最初查到的rgb值去做,那就只要拆分 “绿 - 蓝” 循环就好了。此外,COLOR值是变化的偏移量,越⼩⽣成的颜⾊就越多,⾊彩变化就越细腻。