23 July 2014

Math - Extract the RGB values from a long color

This is a short little peace of code to extract the RGB components of a color stored in a single long value – like they are in Visual Basic. This code is in Apple's Swift language, but that really doesn't matter. You just need to know it's an extension on the Int type and "self" refers to the variable containing the long color.
extension Int {
  func toColor() -> UIColor {
    let r = self % 256
    let g = ((self - r) % 65536) / 256
    let b = (self - g) / 65536
    return UIColor(red: Float(r), green: Float(g), blue: Float(b), alpha: 1)
  }
}

No comments:

Post a Comment