加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift 16 进制颜色字符串转 UIColor

发布时间:2020-12-14 07:18:07 所属栏目:百科 来源:网络整理
导读:import Foundation import UIKit extension UIColor { public convenience init?(hexString: String) { self.init(hexString: hexString,alpha: 1.0) } /** Create non-autoreleased color with in the given hex string and alpha. - parameter hexString:

import Foundation
import UIKit

extension UIColor {

public convenience init?(hexString: String) {
self.init(hexString: hexString,alpha: 1.0)
}

/**
Create non-autoreleased color with in the given hex string and alpha.
- parameter hexString: The hex string,with or without the hash character.
- parameter alpha: The alpha value,a floating value between 0 and 1.
- returns: A color with the given hex string and alpha.
*/
public convenience init?(hexString: String,alpha: Float) {
var hex = hexString

// Check for hash and remove the hash
if hex.hasPrefix("#") {
hex = hex.substringFromIndex(hex.startIndex.advancedBy(1))
}

if (hex.rangeOfString("(^[0-9A-Fa-f]{6}$)|(^[0-9A-Fa-f]{3}$)",options: .RegularExpressionSearch) != nil) {

// Deal with 3 character Hex strings
if hex.characters.count == 3 {
let redHex = hex.substringToIndex(hex.startIndex.advancedBy(1))
let greenHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(1),end: hex.startIndex.advancedBy(2)))
let blueHex = hex.substringFromIndex(hex.startIndex.advancedBy(2))

hex = redHex + redHex + greenHex + greenHex + blueHex + blueHex
}

let redHex = hex.substringToIndex(hex.startIndex.advancedBy(2))
let greenHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(2),end: hex.startIndex.advancedBy(4)))
let blueHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(4),end: hex.startIndex.advancedBy(6)))

var redInt: CUnsignedInt = 0
var greenInt: CUnsignedInt = 0
var blueInt: CUnsignedInt = 0

NSScanner(string: redHex).scanHexInt(&redInt)
NSScanner(string: greenHex).scanHexInt(&greenInt)
NSScanner(string: blueHex).scanHexInt(&blueInt)

self.init(red: CGFloat(redInt) / 255.0,green: CGFloat(greenInt) / 255.0,blue: CGFloat(blueInt) / 255.0,alpha: CGFloat(alpha))
}
else {
// Note:
// The swift 1.1 compiler is currently unable to destroy partially initialized classes in all cases,
// so it disallows formation of a situation where it would have to. We consider this a bug to be fixed
// in future releases,not a feature. -- Apple Forum
self.init()
return nil
}
}
}


https://github.com/thii/SwiftHEXColors/blob/master/Sources/SwiftHEXColors.swift

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读