https://github.com/potato512/SYSwiftLearning
swift中使用UIColor时,除了使用系统自带的颜色外,还可以自定义随机颜色,或按照指定颜色值&透明度进行设置颜色。
效果图:
源代码:
/// 设置随机颜色
class func UIColorRandom() -> UIColor
{
let color: UIColor = UIColor.init(red: (((CGFloat)((random() % 256)) / 255.0)), green: (((CGFloat)((random() % 256)) / 255.0)), blue: (((CGFloat)((random() % 256)) / 255.0)), alpha: 1.0);
return color;
}
/// 设置颜色(RGB:0.0~255.0) 示例:UIColorRGB(100, 100, 100)
class func UIColorRGB(R:CGFloat, G:CGFloat, B:CGFloat) -> UIColor
{
return UIColorRGB_Alpha(R, G: G, B: B, alpha: 1.0);
}
/// 设置颜色与透明度(RGB:0.0~255.0;alpha:0.0~1.0) 示例:UIColorRGB_Alpha(100.0, 100.0, 20.0, 1.0)
class func UIColorRGB_Alpha(R:CGFloat, G:CGFloat, B:CGFloat, alpha:CGFloat) -> UIColor
{
let color = UIColor.init(red: (R / 255.0), green: (G / 255.0), blue: (B / 255.0), alpha: alpha);
return color;
}
/// 设置颜色 示例:UIColorHex(0x26A7E8)
class func UIColorHex(value:UInt32) -> UIColor
{
return UIColorHex_Alpha(value, alpha: 1.0);
}
/// 设置颜色与透明度 示例:UIColorHEX_Alpha(0x26A7E8, 0.5)
class func UIColorHex_Alpha(value:UInt32, alpha:CGFloat) -> UIColor
{
let color = UIColor.init(red: (((CGFloat)((value & 0xFF0000) >> 16)) / 255.0), green: (((CGFloat)((value & 0xFF0000) >> 16)) / 255.0), blue: (((CGFloat)((value & 0xFF0000) >> 16)) / 255.0), alpha: alpha)
return color
}
代码使用示例:
let randomView = UIView.init(frame: CGRectMake(10.0, 80.0, 60.0, 20.0))
self.view.addSubview(randomView);
randomView.backgroundColor = UIColorTools.UIColorRandom()
let hexAlphaView = UIView.init(frame: CGRectMake(10.0, 120.0, 60.0, 60.0))
self.view.addSubview(hexAlphaView);
hexAlphaView.backgroundColor = UIColorTools.UIColorHex_Alpha(0xadaddf, alpha: 0.3)
let hexView = UIView.init(frame: CGRectMake(80.0, 120.0, 60.0, 60.0))
self.view.addSubview(hexView);
hexView.backgroundColor = UIColorTools.UIColorHex(0x663215)
let rgbAlphaView = UIView.init(frame: CGRectMake(10.0, 200.0, 30.0, 30.0))
self.view.addSubview(rgbAlphaView);
rgbAlphaView.backgroundColor = UIColorTools.UIColorRGB_Alpha(200.0, G: 230.0, B: 25.0, alpha: 0.5);
let rgbView = UIView.init(frame: CGRectMake(50.0, 200.0, 30.0, 30.0))
self.view.addSubview(rgbView);
rgbView.backgroundColor = UIColorTools.UIColorRGB(20.0, G: 15.3, B: 55.0)