I am looking for a robust (I mean working in all multi-munitor configuration) algo to convert a cocoa point/rect to carbon equivalent and the reverse operation.
I've googled but was unable to find something which work properly.
Thanks in advance for your help.
Regards,
After several iterations I got to the following category on NSScreen:
+ (NSScreen*) screenWithPoint: (NSPoint) p
{
for (NSScreen *candidate in [NSScreen screens])
if (NSPointInRect(p, [candidate frame]))
return candidate;
return nil;
}
+ (NSScreen*) screenWithMenuBar
{
return [self screenWithPoint:NSZeroPoint];
}
+ (float) menuScreenHeight
{
return NSMaxY([[self screenWithMenuBar] frame]);
}
+ (CGPoint) carbonPointFrom: (NSPoint) cocoaPoint
{
return CGPointMake(cocoaPoint.x, [self menuScreenHeight] - cocoaPoint.y);
}
+ (NSPoint) cocoaPointFrom: (CGPoint) carbonPoint
{
return NSMakePoint(carbonPoint.x, [self menuScreenHeight] - carbonPoint.y);
}
This works fine even with multiple displays.
The posted code from Apple's code from UIElementInspector turn out to be buggy, in that it doesn't account for the origin of a non-main screen. The fixed (and refactored) code looks like this:
+ (CGPoint)carbonScreenPointFromCocoaScreenPoint:(NSPoint)cocoaPoint {
NSScreen* foundScreen = nil;
NSRect screenFrame;
for (NSScreen* screen in [NSScreen screens]) {
screenFrame = [screen frame];
if (NSPointInRect(cocoaPoint, screenFrame)) {
foundScreen = screen;
break;
}
}
if (! foundScreen) return CGPointMake(0.0, 0.0);
return CGPointMake(cocoaPoint.x,
screenFrame.origin.y + screenFrame.size.height - cocoaPoint.y);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With