Skip to content

Instantly share code, notes, and snippets.

@ochim
Created November 27, 2019 03:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ochim/00db5d4f01a57c52d3c3ce6245b33de1 to your computer and use it in GitHub Desktop.
Save ochim/00db5d4f01a57c52d3c3ce6245b33de1 to your computer and use it in GitHub Desktop.
UIColorをカラーコードで生成する
import UIKit

extension UIColor {
    convenience init(hex: String, alpha: CGFloat) {
        let v = Int("000000" + hex, radix: 16) ?? 0
        let r = CGFloat(v / Int(powf(256, 2)) % 256) / 255
        let g = CGFloat(v / Int(powf(256, 1)) % 256) / 255
        let b = CGFloat(v / Int(powf(256, 0)) % 256) / 255
        self.init(red: r, green: g, blue: b, alpha: min(max(alpha, 0), 1))
    }

    convenience init(hex: String) {
        self.init(hex: hex, alpha: 1.0)
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment