2

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!

Community
  • 1
  • 1
Aggressor
  • 13,323
  • 24
  • 103
  • 182

1 Answers1

5

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)
Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Wow! I never knew any such difference between functions & methods (they always meant the same thing), that REALLY clears things up thank you. Also thanks for pointing out the allocation difference as well, I've been stuck on this a while. Big thank you! – Aggressor Jan 02 '15 at 17:58