Swift 16 进制颜色字符串转 UIColor

Swift 16 进制颜色字符串转 UIColor,第1张

概述import Foundation import UIKit extension UIColor {          public convenience init?(hexString: String) {         self.init(hexString: hexString, alpha: 1.0)     }          /**      Create non-autorel

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

总结

以上是内存溢出为你收集整理的Swift 16 进制颜色字符串转 UIColor全部内容,希望文章能够帮你解决Swift 16 进制颜色字符串转 UIColor所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1079944.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存