I'm trying to get the CGColor of a specifiy point from my NSImage (png file). This function is called on NSViews which can be dragged over my NSImageView. Then this function should set a variable (defaultColor) to the Color which is exactly at the position from the NSView on the NSImageView. For testing I then colored each NSView to the color stored in the variable before (so to that color where the NSView is positioned on the NSImageView). How you can see in the screenshots for example I displayed a 300x300 image containing four different colors in the NSImageView. The colors will be detected right, but it seems like the colors are swapped horizontally. The colors on the top will be measured when the NSViews are on the bottom and the colors on the bottom will be measured when the NSViews are on the top.
Is the byte order wrong? How I can swap this? I already read How do I get the color of a pixel in a UIImage with Swift? and Why do I get the wrong color of a pixel with following code?. Thats from where I have the code I use which I changed a little bit:
func setDefaulColor(image: NSImage)
{
let posX = self.frame.origin.x + (self.frame.width / 2)
let posY = self.frame.origin.y + (self.frame.height / 2)
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 1
if posX <= image.size.width && posY <= image.size.height
{
var imageRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
let imageRef = image.cgImage(forProposedRect: &imageRect, context: nil, hints: nil)
var pixelData = imageRef!.dataProvider!.data
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
let pixelInfo: Int = Int(posY) * imageRef!.bytesPerRow + Int(posX) * 4
r = CGFloat(data[pixelInfo]) / CGFloat(255.0)
g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0)
b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0)
a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0)
}
self.defaultColor = CGColor(red: r, green: g, blue: b, alpha: a)
setNeedsDisplay(NSRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height))
}
Here are some screenshots:
The PNG-file displayed by the NSImageView should be in the RGBA format. How you can see I think the colors extracted right from the pixeldata:
r = CGFloat(data[pixelInfo]) / CGFloat(255.0)
g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0)
b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0)
a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0)
but it seems the pixeldata is loaded in the wrong order?
Do you know how to change the data order or why this is happening?