Monday 27 June 2016

Creating a UIColor from a hex string

Swift 2.0 version of solution which will handle alpha value of color and with perfect error handling is here:
    func RGBColor(hexColorStr : String) -> UIColor?{
   
        var red:CGFloat = 0.0
        var green:CGFloat = 0.0
        var blue:CGFloat = 0.0
        var alpha:CGFloat = 1.0
   
        if hexColorStr.hasPrefix("#"){
       
            let index   = hexColorStr.startIndex.advancedBy(1)
            let hex     = hexColorStr.substringFromIndex(index)
            let scanner = NSScanner(string: hex)
            var hexValue: CUnsignedLongLong = 0
       
            if scanner.scanHexLongLong(&hexValue)
            {
                if hex.characters.count == 6
                {
                    red   = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
                    green = CGFloat((hexValue & 0x00FF00) >> 8)  / 255.0
                    blue  = CGFloat(hexValue & 0x0000FF) / 255.0
                }
                else if hex.characters.count == 8
                {
                    red   = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
                    green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
                    blue  = CGFloat((hexValue & 0x0000FF00) >> 8)  / 255.0
                    alpha = CGFloat(hexValue & 0x000000FF)         / 255.0
                }
                else
                {
                    print("invalid hex code string, length should be 7 or 9", terminator: "")
                    return nil
                }
            }
            else
            {
                print("scan hex error")
           return nil
            }
        }
   
        let color: UIColor =  UIColor(red:CGFloat(red), green: CGFloat(green), blue:CGFloat(blue), alpha: alpha)
        return color
    }

No comments:

Post a Comment