现在的位置: 首页 > 综合 > 正文

【iOS】用RGB颜色模型实现彩虹渐变

2018年04月22日 ⁄ 综合 ⁄ 共 1060字 ⁄ 字号 评论关闭

粗略的在网上搜索了一下没有找到现成答案,就自己动手实现了一下。

实现思路:

先在网上查到赤橙黄绿青蓝紫的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值是变化的偏移量,越小生成的颜色就越多,色彩变化就越细腻。

抱歉!评论已关闭.