首先很感谢大家的支持与关注。《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 - 1 func 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>
调试环境:Xcode6 Beta
4s和5模拟器都没有问题。用5s測试的时候会提示运算符错误。
猜測是数据类型的问题。可是详细是什么原因没有调试成功,还请各位指教。