参考URL : 【Swift】あるUIColorからあるUIColorへ変化の途中経過のUIColorを作成する
extension UIColor {
class func colorForOffsetPercentage(percentage: CGFloat, beforeColor: UIColor, afterColor: UIColor) -> UIColor {
let beforeRGB = beforeColor.RGBForColor()
let afterRGB = afterColor.RGBForColor()
let actualRed = (afterRGB.red - beforeRGB.red) * percentage + beforeRGB.red
let actualBlue = (afterRGB.blue - beforeRGB.blue) * percentage + beforeRGB.blue
let actualGreen = (afterRGB.green - beforeRGB.green) * percentage + beforeRGB.green
let actualAlpha = (afterRGB.alpha - beforeRGB.alpha) * percentage + beforeRGB.alpha
return UIColor(red: actualRed, green: actualGreen, blue: actualBlue, alpha: actualAlpha)
}
func RGBForColor() -> (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
var red : CGFloat = 0.0
var green: CGFloat = 0.0
var blue : CGFloat = 0.0
var alpha: CGFloat = 0.0
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return (red, green, blue, alpha)
}
}
★ 16進数でUIColorを作成する
extension UIColor {
class func hex (hexStr : NSString, alpha : CGFloat) -> UIColor {
let hexString = hexStr.stringByReplacingOccurrencesOfString("#", withString: "")
let scanner = NSScanner(string: hexString)
var color: UInt32 = 0
if scanner.scanHexInt(&color) {
let r = CGFloat((color & 0xFF0000) >> 16) / 255.0
let g = CGFloat((color & 0x00FF00) >> 8) / 255.0
let b = CGFloat(color & 0x0000FF) / 255.0
return UIColor(red:r,green:g,blue:b,alpha:alpha)
} else {
print("invalid hex string")
return UIColor.whiteColor();
}
}
}
let color = UIColor.hex("#FF4500", alpha: 1.0)
color //=> r 1.0 g 0.271 b 0.0 a 1.0
★ UIColor
のクラスメソッドでアクセスできる拡張
public func colorFromDecimalRGB(_ red: CGFloat, _ green: CGFloat, _ blue: CGFloat, alpha: CGFloat = 1.0) -> UIColor {
return UIColor(
red: red / 255.0,
green: green / 255.0,
blue: blue / 255.0,
alpha: alpha
)
}
extension UIColor {
// MARK: Custom Defined Colors
/// Dark Blue Aztec
class var aztec: UIColor {
return colorFromDecimalRGB(38, 39, 41)
}
/// Light Cream Color
class var lightCream: UIColor {
return colorFromDecimalRGB(232, 234, 221)
}
/// Cream Color
class var cream: UIColor {
return colorFromDecimalRGB(229, 231, 218)
}
/// Swirl Color
class var swirl: UIColor {
return colorFromDecimalRGB(228, 221, 202)
}
/// Travertine Color
class var travertine: UIColor {
return colorFromDecimalRGB(214, 206, 195)
}
/// Green
class var ufoGreen: UIColor {
return colorFromDecimalRGB(64, 186, 145)
}
class var textGrey: UIColor {
return colorFromDecimalRGB(146, 146, 146)
}
}