Swift hex color conversion

import UIKit


extensionUIColor {

    //Initialize the color with a numerical value to facilitate the generation of the hexadecimal color indicated on the design drawing

    convenience init(valueRGB: UInt, alpha: CGFloat) {

        self.init(

            red: CGFloat((valueRGB & 0xFF0000) >> 16) / 255.0,

            green: CGFloat((valueRGB & 0x00FF00) >> 8) / 255.0,

            blue: CGFloat(valueRGB & 0x0000FF) / 255.0,

            alpha: alpha

        )

    }

    convenience init(hexColor: String) {

        

        // Create UIColor with hex color

        // store the converted value

        var red:UInt32 = 0, green:UInt32 = 0, blue:UInt32 = 0

        

        // Convert separately for conversion

        Scanner(string: hexColor[0..<2]).scanHexInt32(&red)


        Scanner(string: hexColor[2..<4]).scanHexInt32(&green)

        

        Scanner(string: hexColor[4..<6]).scanHexInt32(&blue)

        

        self.init(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: 1.0)

    }

}


extensionString {

    

    // String uses subscript to intercept the string

    // Example: "Example String"[0..<2] results in "Example"

    subscript (r: Range<Int>) -> String {

        get {

            let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)

            let endIndex = self.index(self.startIndex, offsetBy: r.upperBound)

            

            return self[startIndex..<endIndex]

        }

    }

}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325770745&siteId=291194637