swift中十六进制字符串转颜色及颜色渐变

来源:互联网 发布:wpa2psk破解软件 编辑:程序博客网 时间:2024/06/04 19:24

在开发中经常使用到十六进制颜色,用起来比较方便,因此写了个颜色常用方法的扩展类:

demo源码:
https://github.com/CoderJon/CJExtensionColor-swift

RGB形式

这个只是简单的将除数的255单独拿出来,避免冗余

convenience init(r: CGFloat, g: CGFloat, b: CGFloat, alpha: CGFloat = 1.0) {    self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: alpha)    }

十六进制字符串转化成颜色

这里需要注意的几个步骤:

  • 保证输入的是大于6个字符串
  • 截取前面的无用字符
  • 分别截取十六进制的字符串
  • 扫描转化成CGFloat
convenience init?(hex: String, alpha: CGFloat = 1.0) {        guard hex.characters.count >= 6 else {            return nil        }        var temHex = hex.uppercased()        if temHex.hasPrefix("0x") || temHex.hasPrefix("##") || temHex.hasPrefix("0X"){            temHex = (temHex as NSString).substring(from: 2)        }        if temHex.hasPrefix("#") {            temHex = (temHex as NSString).substring(from: 1)        }        var range = NSRange(location: 0, length: 2)        let rHex = (temHex as NSString).substring(with: range)        range.location = 2        let gHex = (temHex as NSString).substring(with: range)        range.location = 4        let bHex = (temHex as NSString).substring(with: range)        var r: UInt32 = 0, g: UInt32 = 0, b: UInt32 = 0        Scanner(string: rHex).scanHexInt32(&r)        Scanner(string: gHex).scanHexInt32(&g)        Scanner(string: bHex).scanHexInt32(&b)        self.init(r: CGFloat(r), g: CGFloat(g), b: CGFloat(b))    }

生成随机颜色

class func randomColor() -> UIColor {        return UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256)))    }

生成渐变色

class func getRGBDelta(_ firstColor: UIColor, _ secondColor: UIColor) -> (rDelta: CGFloat, gDelta: CGFloat, bDelta: CGFloat){        let firstRGB = firstColor.getRGB()        let secondRGB = secondColor.getRGB()        return (firstRGB.0 - secondRGB.0, firstRGB.1 - secondRGB.1, firstRGB.2 - secondRGB.2)    }    func getRGB() -> (CGFloat, CGFloat, CGFloat) {        guard let cmps = cgColor.components else {            fatalError("Ensure that the color is RGB")        }        return (cmps[0] * 255, cmps[1] * 255, cmps[2] * 255)    }
原创粉丝点击