Skip to content

Instantly share code, notes, and snippets.

@dhavaln
Created September 4, 2015 10:13

Revisions

  1. dhavaln created this gist Sep 4, 2015.
    37 changes: 37 additions & 0 deletions ViewController.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    func extractColor(image: UIImage){
    let pixel = UnsafeMutablePointer<CUnsignedChar>.alloc(4)
    let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceRGB()
    let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
    let context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, bitmapInfo)
    CGContextDrawImage(context, CGRectMake(0, 0, 1, 1), image.CGImage)

    var color: UIColor? = nil

    if pixel[3] > 0 {
    var alpha:CGFloat = CGFloat(pixel[3]) / 255.0
    var multiplier:CGFloat = alpha / 255.0

    color = UIColor(red: CGFloat(pixel[0]) * multiplier, green: CGFloat(pixel[1]) * multiplier, blue: CGFloat(pixel[2]) * multiplier, alpha: alpha)
    }else{

    color = UIColor(red: CGFloat(pixel[0]) / 255.0, green: CGFloat(pixel[1]) / 255.0, blue: CGFloat(pixel[2]) / 255.0, alpha: CGFloat(pixel[3]) / 255.0)
    }

    if color != nil {
    println( self.toHexString(color!) )
    }
    pixel.dealloc(4)
    }

    func toHexString(color: UIColor) -> String {
    var r:CGFloat = 0
    var g:CGFloat = 0
    var b:CGFloat = 0
    var a:CGFloat = 0

    color.getRed(&r, green: &g, blue: &b, alpha: &a)

    let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0

    return String(format:"#%06x", rgb)
    }