Converting between Cocoa and Carbon coordinates?
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 wor开发者_运维问答k 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);
}
Or take Apple's code from UIElementInspector sample project:
+ (CGPoint)carbonScreenPointFromCocoaScreenPoint:(NSPoint)cocoaPoint
{
NSScreen *foundScreen = nil;
CGPoint thePoint;
for (NSScreen *screen in [NSScreen screens])
{
if (NSPointInRect(cocoaPoint, [screen frame]))
{
foundScreen = screen;
}
}
if (foundScreen)
{
CGFloat screenHeight = [foundScreen frame].size.height;
thePoint = CGPointMake(cocoaPoint.x, screenHeight - cocoaPoint.y - 1);
}
else
{
thePoint = CGPointMake(0.0, 0.0);
}
return thePoint;
}
精彩评论