在Cocoa和Carbon坐标之间转换?

时间:2010-11-14 21:11:14

标签: objective-c cocoa macos-carbon

我正在寻找一个强大的(我的意思是在所有多维护配置中工作)算法将可可点/矩形转换为碳当量和反向操作。

我用谷歌搜索但无法找到正常工作的东西。

提前感谢您的帮助。

此致

3 个答案:

答案 0 :(得分:3)

经过几次迭代后,我在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);
}

即使有多个显示器,这也能正常工作。

答案 1 :(得分:1)

来自UIElementInspector的Apple代码中发布的代码结果是错误的,因为它没有考虑非主屏幕的来源。固定(和重构)代码如下所示:

+ (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);
}

答案 2 :(得分:0)

或者从UIElementInspector示例项目中获取Apple的代码:

+ (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;
}