swift的hexColor

作者: 蒋昉霖 | 来源:发表于2017-02-15 11:30 被阅读330次

网上找的第三方,color都是字符串去取,内部实现还需要去转一层,看着烦,就简单写了方法

import UIKit


extension UIColor {

    /// hexColor
    convenience init(hex: UInt32) {
        let r: CGFloat = CGFloat((hex & 0xFF000000) >> 24) / 255.0
        let g: CGFloat = CGFloat((hex & 0x00FF0000) >> 16) / 255.0
        let b: CGFloat = CGFloat((hex & 0x0000FF00) >> 8) / 255.0
        let a: CGFloat = CGFloat(hex & 0x000000FF) / 255.0
        self.init(red: r, green: g, blue: b, alpha: a)
    }
    
    /// 创建一张纯色的图片的方法
    func toImage(size: CGSize) -> UIImage {
        UIGraphicsBeginImageContext(size);
        let context = UIGraphicsGetCurrentContext();
        context?.setFillColor(self.cgColor)
        context?.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
        let image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image!;
    }
    
    
}


https://github.com/XHJiang/swift-hexColor

相关文章

网友评论

    本文标题:swift的hexColor

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