将16进制的颜色值变成UIColor

HTML的颜色值都是16进制的,这卖代码用HTML的16上前制颜色值转换成为UIColor对象(RGB)。

例子: 用这个16色的做的蒙版效果,附带透明度20%的需求
//  mengbanView.backgroundColor = UIColor.ZNColor_16RGB_alpha(hex: "#000000", alpha: 0.2)

import UIKit

extension UIColor {
   static func ZNColor_16RGB (hex:String) -> UIColor {
        var cString:String = hex.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
        if (cString.hasPrefix("#")) {
            cString = (cString as NSString).substring(from: 1)
        }
        let rString = (cString as NSString).substring(to: 2)
        let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2)
        let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2)
        var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
        Scanner(string: rString).scanHexInt32(&r)
        Scanner(string: gString).scanHexInt32(&g)
        Scanner(string: bString).scanHexInt32(&b)
        return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
    }

   static func ZNColor_16RGB_alpha (hex:String, alpha:CGFloat) -> UIColor {
        var cString:String = hex.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
        if (cString.hasPrefix("#")) {
            cString = (cString as NSString).substring(from: 1)
        }
        let rString = (cString as NSString).substring(to: 2)
        let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2)
        let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2)
        var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
        Scanner(string: rString).scanHexInt32(&r)
        Scanner(string: gString).scanHexInt32(&g)
        Scanner(string: bString).scanHexInt32(&b)
        return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha)
    }
}
+ (UIColor *) colorFromHexRGB:(NSString *) inColorString
{
 UIColor *result = nil;
 unsigned int colorCode = 0;
 unsigned char redByte, greenByte, blueByte;

 if (nil != inColorString)
 {
  NSScanner *scanner = [NSScanner scannerWithString:inColorString];
  (void) [scanner scanHexInt:&colorCode;]; // ignore error
 }
 redByte = (unsigned char) (colorCode >> 16);
 greenByte = (unsigned char) (colorCode >> 8);
 blueByte = (unsigned char) (colorCode); // masks off high bits
 result = [UIColor
            colorWithRed: (float)redByte / 0xff
            green: (float)greenByte/ 0xff
            blue: (float)blueByte / 0xff
            alpha:1.0];    
 return result;
}
//该片段来自于http://outofmemory.cn

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图