color conversion

The first way is to add an extension to String

extension String {
    /// 将十六进制颜色转换为UIColor
    func uiColor() -> UIColor {
        // 存储转换后的数值
        var red:UInt32 = 0, green:UInt32 = 0, blue:UInt32 = 0

        // 分别转换进行转换
        Scanner(string: self[0..<2]).scanHexInt32(&red)

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

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

        return UIColor(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: 1.0)
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

The second way is to add an extension to UIColor

import UIKit

extension UIColor {

    /// 用十六进制颜色创建UIColor
    ///
    /// - Parameter hexColor: 十六进制颜色 (0F0F0F)
    convenience init(hexColor: String) {

        // 存储转换后的数值
        var red:UInt32 = 0, green:UInt32 = 0, blue:UInt32 = 0

        // 分别转换进行转换
        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)
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

Extensions that need to be used in both ways

extension String {

    /// String使用下标截取字符串
    /// 例: "示例字符串"[0..<2] 结果是 "示例"
    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]
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
This article is reproduced from: https://blog.csdn.net/Pointee/article/details/52276588

Guess you like

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