67
61

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SwiftでHexColor(#34495eみたいなやつ)

Last updated at Posted at 2014-09-23

Objective-Cでよく使っていたUIColorカテゴリをswiftで書き換えたので載っけます。
Webなどでよく使われる16進表記の色をUIColorに変換します。
文字の先頭には「#」がついていてもいなくても変換することができる仕様です。
不正な文字列が来たら"invalid hex string"と出力され、whitecolorが返ってきます。

extension UIColor {
    class func hexStr (var hexStr : NSString, var alpha : CGFloat) -> UIColor {
        hexStr = hexStr.stringByReplacingOccurrencesOfString("#", withString: "")
        let scanner = NSScanner(string: hexStr as String)
        var color: UInt32 = 0
        if scanner.scanHexInt(&color) {
            let r = CGFloat((color & 0xFF0000) >> 16) / 255.0
            let g = CGFloat((color & 0x00FF00) >> 8) / 255.0
            let b = CGFloat(color & 0x0000FF) / 255.0
            return UIColor(red:r,green:g,blue:b,alpha:alpha)
        } else {
            print("invalid hex string")
            return UIColor.whiteColor();
        }
    }
}

利用する時は↓のように使って下さい。

UIColor.hexStr("34495e", alpha: 1)
67
61
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
67
61

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?