将16进制的颜色值转换成UIColor对象
@para:
hexString: 生成颜色对象的16进制字符串
alpha:颜色的透明度,默认1.0
@return 返回生成的UIColor对象
extension UIColor {
public class func color(hexString: String, alpha: CGFloat? = 1.0) -> UIColor {
var cString = hexString.trimmingCharacters(in:.whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
// cString = cString[(from: cString.index(after: cString.startIndex))
cString = String(cString[cString.index(after: cString.startIndex)..<cString.endIndex])
}
if (cString.count != 6) {
return UIColor.clear
}
// let rString = cString.substring(to: cString.index(cString.startIndex, offsetBy: 2))
let rString = cString[..<cString.index(cString.startIndex, offsetBy: 2)]
// let gString = cString.substring(with: cString.index(cString.startIndex, offsetBy: 2)..<cString.index(cString.startIndex, offsetBy: 4))
let gString = cString[cString.index(cString.startIndex, offsetBy: 2)..<cString.index(cString.startIndex, offsetBy: 4)]
// let bString = cString.substring(from: cString.index(cString.endIndex, offsetBy: -2))
let bString = cString[cString.index(cString.endIndex, offsetBy: -2)..<cString.endIndex]
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
Scanner(string: String(rString)).scanHexInt32(&r)
Scanner(string: String(gString)).scanHexInt32(&g)
Scanner(string: String(bString)).scanHexInt32(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha!)
}
}
使用颜色值生成图片
@para:
color: 生成图片的颜色的字符串
size:生成图片的大小
@return 返回生成的Image对象
public class func createImage(colorString: String, size: CGSize) -> UIImage? {
var rect = CGRect(origin: CGPoint.zero, size: size)
let co = color(hexString: colorString)
UIGraphicsBeginImageContext(size)
defer {
UIGraphicsEndImageContext()
}
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(co.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
return image
}
使用颜色值生成图片
@para:
color: 生成图片的颜色
size:生成图片的大小
@return 返回生成的Image对象
public class func createImage(color: UIColor, size: CGSize) -> UIImage? {
var rect = CGRect(origin: CGPoint.zero, size: size)
UIGraphicsBeginImageContext(size)
defer {
UIGraphicsEndImageContext()
}
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
return image
}