Created
November 24, 2015 01:08
-
-
Save externvoid/c87afc26a375139ef6d6 to your computer and use it in GitHub Desktop.
ヘキサを整数へ変換、カラーコードからUIColorを作る準備
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
var hex = "ABCDEF" | |
// remove space located at header, trailer | |
let cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString | |
//whitespaceAndNewlineCharacterSet, space, linefeed | |
if ((cString as String).characters.count != 6) { | |
print("Error") | |
} | |
// picking up 2 chars | |
let rString = (cString as NSString).substringWithRange(NSRange(location: 0, length: 2)) | |
let gString = (cString as NSString).substringWithRange(NSRange(location: 2, length: 2)) | |
let bString = (cString as NSString).substringWithRange(NSRange(location: 4, length: 2)) | |
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0; | |
// class culster for conversion from String to various type | |
NSScanner(string: rString).scanHexInt(&r) | |
NSScanner(string: gString).scanHexInt(&g) | |
NSScanner(string: bString).scanHexInt(&b) | |
print(r, g, b) //171 205 239 | |
// Key Point | |
// 1. NSString.stringByTrimmingCharactersInSet、空白改行除去 | |
// 2. NSString.substringWithRange、部分文字列除去 | |
// 3. NSScanner.scanHexInt、Hex2Intヘキサを数字へ変換 | |
~ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment