Swift 4 十六进制转颜色,使用颜色生成图片方法

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

使用颜色值生成图片
@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
}

你可能感兴趣的:(Swift 4 十六进制转颜色,使用颜色生成图片方法)