【问题标题】:Why NSView origin screen coordinate differs from its NSWindow origin screen coordinate?为什么 NSView 原始屏幕坐标与其 NSWindow 原始屏幕坐标不同?
【发布时间】:2021-07-31 16:13:45
【问题描述】:

最初我需要一个 NSWindow -> NSView -> NSView (subview) -> NSRect 的屏幕坐标来进行屏幕捕获。我发现 bitmapImageRepForCachingDisplayInRect 对我的需要来说太慢了(直接从视图中取出矩形),所以我将使用 CGWindowListCreateImage。

当我试图找到我的最终矩形的屏幕坐标时,我遇到了一个我无法弄清楚的奇怪事情:contentView 原点屏幕坐标不等于窗口原点屏幕坐标,即使 contentView 原点是 0, 0 在窗口空间中。

这是我的简化代码:

@interface MyWindowController ()

@end

@implementation MyWindowController

- (void)windowDidLoad {
    [super windowDidLoad];
    
    NSRect rectWindowOnScreen = [[self window] convertRectToScreen:self.window.frame];
    printf("rectWindowOnScreen:%.2f %.2f %.2f %.2f\n", rectWindowOnScreen.origin.x, rectWindowOnScreen.origin.y, rectWindowOnScreen.size.width, rectWindowOnScreen.size.height);
    
    NSRect rectWindowContentArea = [[self window] contentLayoutRect];
    printf("rectWindowContentArea:%.2f %.2f %.2f %.2f\n", rectWindowContentArea.origin.x, rectWindowContentArea.origin.y, rectWindowContentArea.size.width, rectWindowContentArea.size.height);
    
    NSRect rectWindowContentAreaOnScreen = [[self window] convertRectToScreen:[[self window] contentLayoutRect]];
    printf("rectWindowContentAreaOnScreen:%.2f %.2f %.2f %.2f\n", rectWindowContentAreaOnScreen.origin.x, rectWindowContentAreaOnScreen.origin.y, rectWindowContentAreaOnScreen.size.width, rectWindowContentAreaOnScreen.size.height);

    NSRect rectWiew = [[[self window] contentView] frame];
    printf("rectWiew:%.2f %.2f %.2f %.2f\n", rectWiew.origin.x, rectWiew.origin.y, rectWiew.size.width, rectWiew.size.height);
    
    NSRect rectWiewOnScreen = [[self window] convertRectToScreen:[[[self window] contentView] frame]];
    printf("rectWiewOnScreen:%.2f %.2f %.2f %.2f\n", rectWiewOnScreen.origin.x, rectWiewOnScreen.origin.y, rectWiewOnScreen.size.width, rectWiewOnScreen.size.height);

}

@end

结果是:

rectWindowOnScreen:470.00 578.00 480.00 292.00
rectWindowContentArea:0.00 0.00 480.00 270.00
rectWindowContentAreaOnScreen:235.00 289.00 480.00 270.00
rectWiew:0.00 0.00 480.00 270.00
rectWiewOnScreen:235.00 289.00 480.00 270.00

这怎么可能? 235.00 289.00坐标从何而来?

我尝试设置 [[[self window] contentView] setFrameOrigin: 但结果是一样的。

我遇到了死胡同。非常感谢您的帮助,谢谢。

【问题讨论】:

  • 你为什么要在NSWindowController的子类下这样做?
  • 提示:打印window.frame,它已经在屏幕坐标中了。
  • 原来我的代码比较复杂,当我遇到这个问题时,我想在一个更简单的环境中检查它,排除任何干扰的复杂性。所以我只得到一个控制器和一个测试窗口。

标签: objective-c macos coordinate-systems


【解决方案1】:

正如 Willeke 所说,您可以像这样在屏幕坐标中获取窗口框架:

NSRect frameRect = window.frame;

这将包括窗口的标题栏。如果您只想要内容 rect,则不需要显式获取内容视图(如在第四个 printf 语句中)。你可以这样做:

NSRect contentRect = [window contentRectForFrameRect: window.frame];

【讨论】:

    猜你喜欢
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-11
    相关资源
    最近更新 更多