Search code examples
swiftmacoscore-graphicscgimage

How to find the CGColor at a CGPoint in a CGImage


I am trying to find the CGColor at a CGPoint in a CGImage. There are multiple Stack Overflow posts that have something similar (like UIImage instead of CGImage or Objective C instead of Swift), but nothing specific enough to help me.

Does anyone know how to get the color at a point? Thanks.


Solution

  • Im assuming based on your macOS tag that you want to do this on macOS and thus can use NSImage and NSBitmapImageRep:

    let cgImage = //your CGImage
    let bitmap = NSBitmapImageRep(cgImage: cgImage)
    if let colorAtPoint = bitmap.colorAt(x: 0, y: 0) {
      let cgColor = colorAtPoint.cgColor
      print(cgColor)
    }