rgb随机颜色html,随机颜色 & 字符串转RGB

给系统类 UIColor 添加分类。实现随机颜色和字符串转RGB功能。

随机颜色

使用 extension 关键字给 UIColor 添加分类。在 {} 中创建 便利构造方法。

extension UIColor {

// add convenience initializer

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)

}

}

添加类方法,实现颜色随机,RGB的随机数使用 arc4random_uniform() 来生成。

// class function, random the color

class func randomColor() -> UIColor {

return UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256)))

}

在这里,我创建了一个 UICollectionView 来展示每个 item 的背景颜色为随机值。

5950e6684680

十六进制字符转转成 RGB

通过给定的十六进制的字符串,转成对应的RGB值。需要对输入的字符串进行位数判断,转换成大写,然后分贝截取R、G、B对于的字符串,使用 Scanner 类把字符串转成数字。

// convert hexadecimal string to RGB value

convenience init?(hex: String, alpha: CGFloat = 1.0) {

// get the length of string

guard hex.characters.count >= 6 else {

return nil

}

// Convert to uppercased

var tempHex = hex.uppercased()

// prefix 0X/##/#

if tempHex.hasPrefix("0X") || tempHex.hasPrefix("##") {

tempHex = (tempHex as NSString).substring(from: 2)

}

if tempHex.hasPrefix("#") {

tempHex = (tempHex as NSString).substring(from: 1)

}

// cut the string,get the R、G、B separately

var range = NSRange(location: 0, length: 2)

let rHex = (tempHex as NSString).substring(with: range)

range.location = 2

let gHex = (tempHex as NSString).substring(with: range)

range.location = 4

let bHex = (tempHex as NSString).substring(with: range)

// convert the hex string to number

var r: UInt32 = 0, g: UInt32 = 0, b: UInt32 = 0

// convert NSString object to number, pass an UInt32 type address

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))

}

使用时直接调用初始化方法:

view.backgroundColor = UIColor(hex: "0xFF26FF")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值