颜色转换
程序员文章站
2022-03-07 08:59:17
...
第一种方式是给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
第二种方式是给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
两种方式都需要用到的扩展
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
本文转载自: https://blog.csdn.net/Pointee/article/details/52276588
下一篇: Lua的迭代器使用中应该避免的问题和技巧