@@ -15,47 +15,44 @@ public extension UIColor {
1515
1616 - Returns: UIColor
1717 */
18- public static func randomColor( ) -> UIColor {
19- return UIColor (
20- red: CGFloat ( randomFloat ( 0 , 255.0 ) ) / 255.0 ,
21- green: CGFloat ( randomFloat ( 0 , 255.0 ) ) / 255.0 ,
22- blue: CGFloat ( randomFloat ( 0 , 255.0 ) ) / 255.0 ,
23- alpha: 1
24- )
18+ class func random( ) -> UIColor {
19+ return UIColor ( red: randomFloat ( ) / 255 , green: randomFloat ( ) / 255 , blue: randomFloat ( ) / 255 , alpha: 1 )
2520 }
2621
27- /**
28- Generates a random Float between a lower and an upper values.
29-
30- - Parameters:
31- - lower: the lower value
32- - upper: the lower value
33-
34- - Returns: UIColor
35- */
36- fileprivate static func randomFloat( _ lower: Float = 0.0 , _ upper: Float = 1.0 ) -> Float {
37- let r = Float ( arc4random ( ) ) / Float( UInt32 . max)
38- return ( r * ( upper - lower) ) + lower
22+ private class func randomFloat( ) -> CGFloat {
23+ return CGFloat ( Float ( arc4random ( ) ) / Float( UINT32_MAX) ) * 255
3924 }
4025
4126 /**
42- Formats a hex color string to UIColor. If empty, Black. If invalid, White.
27+ Formats a hex color string to UIColor.
4328
4429 - Parameter hex: web format hex color without the #
4530
4631 - Returns: UIColor
4732 */
48- public static func colorFromHex( _ hex: String ) -> UIColor {
49- let scanner = Scanner ( string: hex)
50- //scanner.charactersToBeSkipped = NSCharacterSet.alphanumericCharacterSet.invertedSet
51-
52- var value : UInt32 = 0 ;
53- scanner. scanHexInt32 ( & value)
33+ public convenience init ? ( hexString: String ) {
34+ let r , g , b , a : CGFloat
5435
55- let red = CGFloat ( Float ( Int ( value >> 16 ) & 0x000000FF ) / 255.0 )
56- let green = CGFloat ( Float ( Int ( value >> 8 ) & 0x000000FF ) / 255.0 )
57- let blue = CGFloat ( Float ( Int ( value) & 0x000000FF ) / 255.0 )
36+ if hexString. hasPrefix ( " # " ) {
37+ let start = hexString. index ( hexString. startIndex, offsetBy: 1 )
38+ let hexColor = hexString. substring ( from: start)
39+
40+ if hexColor. characters. count == 8 {
41+ let scanner = Scanner ( string: hexColor)
42+ var hexNumber : UInt64 = 0
43+
44+ if scanner. scanHexInt64 ( & hexNumber) {
45+ r = CGFloat ( ( hexNumber & 0xff000000 ) >> 24 ) / 255
46+ g = CGFloat ( ( hexNumber & 0x00ff0000 ) >> 16 ) / 255
47+ b = CGFloat ( ( hexNumber & 0x0000ff00 ) >> 8 ) / 255
48+ a = CGFloat ( hexNumber & 0x000000ff ) / 255
49+
50+ self . init ( red: r, green: g, blue: b, alpha: a)
51+ return
52+ }
53+ }
54+ }
5855
59- return UIColor ( red : red , green : green , blue : blue , alpha : 1.0 )
56+ return nil
6057 }
6158}
0 commit comments