美文网首页
Swift - RGB、16进制颜色转换

Swift - RGB、16进制颜色转换

作者: 朴子hp | 来源:发表于2018-11-08 22:05 被阅读29次

1.RGB颜色


func kRgbColor(red:CGFloat, green:CGFloat, blue:CGFloat) ->UIColor{

    return UIColor.init(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha:1.0)

}

2.RGBA颜色


func kRgbAColor(red:CGFloat, green:CGFloat, blue:CGFloat, aplha:CGFloat) ->UIColor{

    return UIColor.init(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: aplha)

}

3.16进制颜色转换


func kHexOfColor(hexString:String) ->UIColor{

    var cstr = hexString.trimmingCharacters(in:  CharacterSet.whitespacesAndNewlines).uppercased() as NSString;

    if(cstr.length<6){

        return UIColor.clear;

    }

    if(cstr.hasPrefix("0X")){

        cstr = cstr.substring(from:2)asNSString

    }

    if(cstr.hasPrefix("#")){

        cstr = cstr.substring(from:1)asNSString

    }

    if(cstr.length!=6){

        return UIColor.clear;

    }

    var range =NSRange.init()

    range.location=0

    range.length=2

    //red

    let rStr = cstr.substring(with: range);

    //green

    range.location=2;

    let gStr = cstr.substring(with: range)

    //blue

    range.location=4;

    let bStr = cstr.substring(with: range)

    var r :UInt32=0x0;

    var g :UInt32=0x0;

    var b :UInt32=0x0;

    Scanner.init(string: rStr).scanHexInt32(&r);

    Scanner.init(string: gStr).scanHexInt32(&g);

    Scanner.init(string: bStr).scanHexInt32(&b);

    return UIColor(red:CGFloat(r)/255.0, green:CGFloat(g)/255.0, blue:CGFloat(b)/255.0, alpha:CGFloat(1.0))

}

项目中的具体使用

1.  kRgbColor(red:238, green:238, blue:238)  

2.  kRgbAColor(red:238, green:237, blue:236, aplha:0.5)

3.  kHexOfColor(hexString:"0xF6BF3E")

相关文章

网友评论

      本文标题:Swift - RGB、16进制颜色转换

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