HSB 为 色相,饱和度,明度。
HSL 为 色相,饱和度,亮度。
HSV 为色相,饱和度,明度。
HSB 和 HSV 算法一致,HSL稍有区别
参考 CSDN博主「Sunshine_in_Moon」的原创文章 RGB转到HSV和HSL公式
注意:ios中UIColor初始化只接受HSB,该方法返回的hue值范围为0-360,但是iOS中取值范围为0-1,需要将返回的hue除以360
RGB转HSL,参数为rgb(取值范围0-255),返回一个包含hsl的元组
func rgbToHsl(red:CGFloat, green:CGFloat, blue:CGFloat) -> (h:CGFloat, s:CGFloat, l:CGFloat){
let r:CGFloat = red/255
let g:CGFloat = green/255
let b:CGFloat = blue/255
print("r = \(r), g = \(g), b = \(b)")
let Max:CGFloat = max(r, g, b)
let Min:CGFloat = min(r, g, b)
//h 0-360
var h:CGFloat = 0
if Max == Min {
h = 0.0
}else if Max == r && g >= b {
h = 60 * (g-b)/(Max-Min)
} else if Max == r && g < b {
h = 60 * (g-b)/(Max-Min) + 360
} else if Max == g {
h = 60 * (b-r)/(Max-Min) + 120
} else if Max == b {
h = 60 * (r-g)/(Max-Min) + 240
}
print("h = \(h)")
//l 0-1
let l:CGFloat = (r + g + b) / 3
print("l = \(l)")
//s 0-1
var s:CGFloat = 0
if l == 0 || Max == Min {
s = 0
} else if l > 0 && l <= 0.5 {
s = (Max - Min)/(2*l)
} else if l > 0.5 {
s = (Max - Min)/(2 - 2*l)
}
print("s = \(s)")
return (h, s, l)
}
RGB转HSV,参数为rgb(取值范围0-255),返回一个包含hsv的元组
func rgbToHsv(red:CGFloat, green:CGFloat, blue:CGFloat) -> (h:CGFloat, s:CGFloat, v:CGFloat){
let r:CGFloat = red/255
let g:CGFloat = green/255
let b:CGFloat = blue/255
print("r = \(r), g = \(g), b = \(b)")
let Max:CGFloat = max(r, g, b)
let Min:CGFloat = min(r, g, b)
//h 0-360
var h:CGFloat = 0
if Max == Min {
h = 0.0
}else if Max == r && g >= b {
h = 60 * (g-b)/(Max-Min)
} else if Max == r && g < b {
h = 60 * (g-b)/(Max-Min) + 360
} else if Max == g {
h = 60 * (b-r)/(Max-Min) + 120
} else if Max == b {
h = 60 * (r-g)/(Max-Min) + 240
}
print("h = \(h)")
//s 0-1
var s:CGFloat = 0
if Max == 0 {
s = 0
} else {
s = (Max - Min)/Max
}
print("s = \(s)")
//v
let v:CGFloat = Max
print("v = \(v)")
return (h, s, v)
}
调用
let hsv = rgbToHsv(red: 255, green: 230, blue: 105)
let color = UIColor(hue: hsv.h/360, saturation: hsv.s, brightness: hsv.v, alpha: 1)
self.view.backgroundColor = color