Skip to content

Instantly share code, notes, and snippets.

@giulio92
Last active December 4, 2018 09:13
Show Gist options
  • Select an option

  • Save giulio92/69e4f74217422154bb25d2a35d6710f8 to your computer and use it in GitHub Desktop.

Select an option

Save giulio92/69e4f74217422154bb25d2a35d6710f8 to your computer and use it in GitHub Desktop.

Revisions

  1. giulio92 renamed this gist Apr 16, 2016. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. giulio92 created this gist Apr 16, 2016.
    28 changes: 28 additions & 0 deletions getPixelColor
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    func getColorForPixel(image:CGImageRef, point:CGPoint) -> UIColor {
    let imageWidth = CGImageGetWidth(image)
    let imageHeight = CGImageGetHeight(image)
    let imageRect = CGRect(x: 0, y: 0, width: imageWidth, height: imageHeight)

    let bitmapBytesForRow = Int(imageWidth * 4)
    let bitmapByteCount = bitmapBytesForRow * Int(imageHeight)

    let colorSpace = CGColorSpaceCreateDeviceRGB()

    let bitmapMemory = malloc(bitmapByteCount)
    let bitmapInformation = CGImageAlphaInfo.PremultipliedFirst.rawValue

    let colorContext = CGBitmapContextCreate(bitmapMemory, imageWidth, imageHeight, 8, bitmapBytesForRow, colorSpace, bitmapInformation)

    CGContextClearRect(colorContext, imageRect)
    CGContextDrawImage(colorContext, imageRect, image)

    let data = CGBitmapContextGetData(colorContext)
    let dataType = UnsafePointer<UInt8>(data)

    let offset = 4 * (Int(imageWidth) * Int(point.y)) + Int(point.x)
    let redComponent = CGFloat(dataType[offset + 1])/255.0
    let greenComponent = CGFloat(dataType[offset + 2])/255.0
    let blueComponent = CGFloat(dataType[offset + 3])/255.0

    return UIColor(red: redComponent, green: greenComponent, blue: blueComponent, alpha: 1.0)
    }