美文网首页swift学习记录
Swift:16进制颜色转RGB

Swift:16进制颜色转RGB

作者: 伯wen | 来源:发表于2018-08-01 11:06 被阅读41次
  • 代码
import UIKit

extension UIColor {
    
    /// 24位16进制颜色
    ///
    /// - Parameter hex: 24位16进制 数
    convenience init(hex: UInt32) {
        let r = (hex & 0xff0000) >> 16
        let g = (hex & 0x00ff00) >> 8
        let b = hex & 0x0000ff
        self.init(r: UInt8(r), g: UInt8(g), b: UInt8(b))
    }
    
    /// 获取 UIColor
    ///
    /// - Parameters:
    ///   - r: 红    取值: 0-255
    ///   - g: 绿    取值: 0-255
    ///   - b: 蓝    取值: 0-255
    convenience init(r: UInt8, g: UInt8, b: UInt8) {
        self.init(red: CGFloat(r) / 255.0, green:  CGFloat(g) / 255.0, blue:  CGFloat(b) / 255.0, alpha: 1)
    }
    
    /// 随机色
    class var random: UIColor {
        return UIColor(r: UInt8(arc4random_uniform(256)), g: UInt8(arc4random_uniform(256)), b: UInt8(arc4random_uniform(256)))
    }
}
  • 调用
UIColor(hex: 0xf6f6f6)
UIColor.random
UIColor(r: 234, g: 234, b: 234)

相关文章

网友评论

    本文标题:Swift:16进制颜色转RGB

    本文链接:https://www.haomeiwen.com/subject/eoplvftx.html