swift—UIColor十六进制
Posted st646889325
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift—UIColor十六进制相关的知识,希望对你有一定的参考价值。
- 新建一个文件UIColor+hex.swift
2.代码
import Foundation
import UIKit
extension UIColor
class func colorWithHex(hexStr:String) -> UIColor
return UIColor.colorWithHex(hexStr : hexStr, alpha:1)
class func colorWithHex(hexStr:String, alpha:Float) -> UIColor
var cStr = hexStr.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased() as NSString;
if(cStr.length < 6)
return UIColor.clear;
if(cStr.hasPrefix("0x"))
cStr = cStr.substring(from: 2) as NSString
if(cStr.hasPrefix("#"))
cStr = cStr.substring(from: 1) as NSString
if(cStr.length != 6)
return UIColor.clear
let rStr = (cStr as NSString).substring(to: 2)
let gStr = ((cStr as NSString).substring(from: 2) as NSString).substring(to: 2)
let bStr = ((cStr as NSString).substring(from: 4) as NSString).substring(to: 2)
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.init(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: CGFloat(alpha));
- 调用
UIColor.colorWithHex(hexStr: "#e36464")
UIColor.colorWithHex(hexStr: "#e36464",alpha:1)
以上是关于swift—UIColor十六进制的主要内容,如果未能解决你的问题,请参考以下文章