假设我有一个十六进制,例如:5fc9f8
是否有接受“黑暗等级”(-10到10)的函数并返回反映该值的十六进制?
在黑暗中,我的意思是在颜色上添加黑色/去除黑色。
答案 0 :(得分:3)
import UIKit
extension String {
subscript (range: Range<Int>) -> String {
return range.startIndex < 0 || range.endIndex > count(self) ? "Out of Range" : substringWithRange(Range(start:advance(startIndex,range.startIndex),end:advance(startIndex,range.endIndex)))
}
var hexaCGFloat: CGFloat {
return CGFloat(strtoul(self, nil, 16))
}
}
extension UIColor {
var rgbComponents:(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
var r:CGFloat = 0, g:CGFloat = 0, b:CGFloat = 0, a:CGFloat = 0
if getRed(&r, green: &g, blue: &b, alpha: &a) {
return (r,g,b,a)
}
return (0,0,0,0)
}
var hsbComponents:(hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat) {
var h:CGFloat = 0, s:CGFloat = 0, b:CGFloat = 0, a:CGFloat = 0
if getHue(&h, saturation: &s, brightness: &b, alpha: &a){
return (h,s,b,a)
}
return (0,0,0,0)
}
var hslComponents:(hue: CGFloat, saturation: CGFloat, lightness: CGFloat, alpha: CGFloat) {
let rgb = rgbComponents, hsb = hsbComponents
let maximum = max(rgb.red, rgb.green, rgb.blue)
let minimum = min(rgb.red, rgb.green, rgb.blue)
let range = maximum - minimum
let lightness = (maximum + minimum) / 2.0
let saturation = range == 0 ? 0 : range / { return lightness < 0.5 ? lightness * 2 : 2 - (lightness * 2) }()
return (hsb.hue, saturation, lightness, hsb.alpha)
}
convenience init(hue: CGFloat, var saturation:CGFloat , var lightness:CGFloat , alpha: CGFloat) {
lightness *= 2
saturation *= lightness <= 1 ? lightness : 2 - lightness
self.init(hue: hue, saturation: lightness == 0 ? 0 : (2*saturation)/(lightness+saturation), brightness: (lightness+saturation)/2, alpha: 1)
}
convenience init(htmlColor:String, alpha: Double) {
self.init(red: htmlColor[0...1].hexaCGFloat / 255.0, green: htmlColor[2...3].hexaCGFloat / 255.0, blue: htmlColor[4...5].hexaCGFloat / 255.0, alpha: CGFloat(alpha) )
}
}
<强>测试强>
let color = UIColor(htmlColor: "5fc9f8", alpha: 1)
let colorHSL = color.hslComponents
let lighterColor = UIColor(hue:colorHSL.hue, saturation: colorHSL.saturation, lightness: min(colorHSL.lightness * 1.3,1.0), alpha: 1)
let darkerColor = UIColor(hue:colorHSL.hue, saturation: colorHSL.saturation, lightness: max(colorHSL.lightness * 0.5,0.0), alpha: 1)
答案 1 :(得分:1)
RGB(红绿蓝色,十六进制代码表示的颜色)与亮度等颜色变换不一致。最简单的方法是将RGB颜色转换为HSB(色调饱和度亮度)或HSL(色调饱和度亮度),将亮度或亮度调整到所需亮度,然后将其转换回RGB。
答案 2 :(得分:0)
假设您通过以下方式设置背景颜色:
self.view.backgroundColor = UIColor.redColor()
我不打算告诉你如何将亮度改变一定量,这取决于你,但我会准确地告诉你改变backgroundColor
亮度所需要的东西。 (在这种情况下):
//if you want the full brightness... brightness: 1.0
self.view.backgroundColor = UIColor(hue: 1.0, saturation: 1.0, brightness: 0.5, alpha: 1.0)
这会使亮度降低 50%,因为brightness: 0.5
不是brightness: 1.0
但正如您所看到的,很容易将此功能绑定到增加或减少 backgroundColor
的亮度(在此情况)。
答案 3 :(得分:0)