iosxcodeobjectswiftcgcontextref

Get Color Of Pixel At Point In Swift


I have found an example of Objective-C code that gets the color of a pixel at a point here: How to get the pixel color on touch?

The specific section of code I need help with is where the context is created using CGColorSpaceCreateDeviceRGB:

---This is the Objective-C code

unsigned char pixel[4] = {0};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(pixel,
            1, 1, 8, 4, colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);
CGContextTranslateCTM(context, -point.x, -point.y);

My best attempt looks as follows (I'm not returning anything yet I'm trying to get the context properly first):

---This is my best attempt at a Swift conversion

func getPixelColorAtPoint()
    {
        let pixel = UnsafeMutablePointer<CUnsignedChar>.alloc(1)
        var colorSpace:CGColorSpaceRef = CGColorSpaceCreateDeviceRGB()
        let context = CGBitmapContextCreate(pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: nil, bitmapInfo: CGImageAlphaInfo.PremultipliedLast)

    }

However this gives me an error

Cannot convert the expression's type '(UnsafeMutablePointer<CUnsignedChar>, width: IntegerLiteralConvertible, height: IntegerLiteralConvertible, bitsPerComponent: IntegerLiteralConvertible, bytesPerRow: IntegerLiteralConvertible, space: NilLiteralConvertible, bitmapInfo: CGImageAlphaInfo)' to type 'IntegerLiteralConvertible'

If you could advise how I need to tweak my code above to get the context function paramters entered correctly I would appreciate it thank you!


Solution

  • There are two different problems:

    So this should compile:

    let pixel = UnsafeMutablePointer<CUnsignedChar>.alloc(4)
    var colorSpace = CGColorSpaceCreateDeviceRGB()
    let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
    let context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, bitmapInfo)
    
    // ...
    
    pixel.dealloc(4)
    

    Note that you should allocate space for 4 bytes, not 1.

    Alternatively:

    var pixel : [UInt8] = [0, 0, 0, 0]
    var colorSpace = CGColorSpaceCreateDeviceRGB()
    let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
    let context = CGBitmapContextCreate(UnsafeMutablePointer(pixel), 1, 1, 8, 4, colorSpace, bitmapInfo)