彩虹漸層色 的 Swift 實現

來源:互聯網
上載者:User

標籤:彩虹漸層   swift   rgb顏色模型   

首先非常感謝大家的支援與關注。《Web Color 的 Swfit 實現》一文一經發布,訪問量迅速攀升,讓本人受寵若驚。

為表達感激之情,今天早上把彩虹漸層也順手實現了。


最新代碼&相關資料:https://github.com/duzixi/RainbowColors-with-Swift (持續維護)

產生函數原型:

  • func rainbowColor(x: Float) -> UIColor
參數取值範圍:

      x : 0 ~ 256 * 5 - 1


產生所有彩虹漸層色的樣本:

class ViewController: UIViewController {    override func viewDidLoad() {        super.viewDidLoad()        // Do any additional setup after loading the view, typically from a nib.        let viewHeight:Float = Float(self.view.frame.size.height)        let viewWidth:Float = Float(self.view.frame.size.width)        //Create all Rainbow Colors        let inc:Float = 256 * 5 / viewHeight;        for (var i:Float = 0.0; i < 256 * 5; i += inc) {            let view = UIView();            view.frame = CGRectMake(0, 0 + i / inc, viewWidth, 1);            view.backgroundColor = rainbowColor(i); // <----調用彩虹漸層色函數,參數必須是Float型            self.view.addSubview(view);        }    }    override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()        // Dispose of any resources that can be recreated.    }}

程式執行:



原始碼參照:

(注意:以下原始碼未必最新。最新原始碼請點擊進入本文上方的連結擷取。)

<span style="font-family:Arial;font-size:14px;">////  RainbowColor.swift////  Created by 杜子兮 on 14-6-29.//  Copyright (c) 2014年 lanou. All rights reserved.//import UIKit// x: 0 ~ 256 * 5 - 1func rainbowColor(x :Float) -> UIColor {    var unit:Float = 256    var r:Float = 0, g:Float = 0, b:Float = 0    if ( 0 <= x && x < unit) { //赤 -> 橙 -> 黃        r = unit - 1        g = x    } else if (x < unit * 2) { //黃 -> 綠        r = unit - 1 - x % unit        g = unit - 1    } else if (x < unit * 3) { //綠 -> 青        g = unit - 1 - x % unit / 2        b = x % unit    } else if (x < unit * 4) { //青 -> 藍        g = unit / 2 - 1 - x % unit / 2        b = unit - 1    } else if (x < unit * 5) { //藍 -> 紫        r = x % unit        b = unit - 1    }    return UIColor(red:r / (unit - 1), green:g / (unit - 1), blue:b / (unit - 1), alpha: 1.0)}</span>


程式Bug:

調試環境:Xcode6 Beta

4s和5模擬器都沒有問題,用5s測試的時候會提示運算子錯誤。

推測是資料類型的問題,但是具體是什麼原因沒有調試成功,還請各位不吝賜教。


相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.