1

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.

Ben A.
  • 874
  • 7
  • 23
  • Does this answer your question? [Get Pixel color of UIImage](https://stackoverflow.com/questions/3284185/get-pixel-color-of-uiimage) – AamirR Nov 03 '21 at 20:47

1 Answers1

2

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)
}
jnpdx
  • 45,847
  • 6
  • 64
  • 94
  • The x and y values in colorAt(x:y:) are Ints-- how do I convert from CGFloat to Int without losing precision? – Ben A. Nov 02 '21 at 19:57
  • 2
    This is getting into a tricky area of display resolution, pixels vs points, etc. The `colorAt` returns a value at a specified `pixel` -- that's why `x,y` are `Int`. If you have a `CGFloat` from, say, a position on the screen, you'll need to make sure you're converting between pixels and points. – jnpdx Nov 02 '21 at 20:00
  • Thanks. Is the conversion pixel = point * resolution? – Ben A. Nov 02 '21 at 20:17
  • 1
    This depends on how you have it displayed. Let's say you have a 300 pixel image and it's being displayed in 150 points on the screen -- then your screen density is 2x and each 1 pt on the screen would be 2 px. – jnpdx Nov 02 '21 at 20:20