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

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

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)
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值