【问题标题】:Centering an NSRect with code使用代码将 NSRect 居中
【发布时间】:2012-06-13 07:24:19
【问题描述】:

大家好,我有一个正在处理的项目,我注意到我在某个 x、y 坐标处绘制的 NSRect 将是我正在处理的分辨率的中心,如果分辨率改变。我明白这一切是如何运作的。

问题是我的项目将以多种分辨率显示有没有人知道将 NSrect 居中的可能解决方案,无论屏幕处于何种方面或分辨率。我将我的类声明为具有自定义绘图的 NSPanel .关于可能的解决方案的任何想法都会有所帮助。谢谢大家。

这是 NSRect x, y, width, height

NSRect windowFrame = NSMakeRect(400, 500, 500, 100);

然后

window = [[Mainbox alloc] initWithContentRect:windowFrame 
                                          styleMask:NSBorderlessWindowMask 
                                            backing:NSBackingStoreBuffered 
                                              defer:NO];

【问题讨论】:

    标签: cocoa


    【解决方案1】:

    要将一个矩形置于另一个矩形的中心,请将内部矩形的原点设置为((外部矩形的原点加上外部矩形大小的一半)减去内部矩形大小的一半)。

    但是,你不需要这样做。

    在您订购之前向您的窗口发送center 消息。它会适当地居中 HIG。

    您可能希望使用起始于 0,0 而不是某个任意点的起始矩形来初始化窗口,以确保如果有主菜单屏幕,则该屏幕将被视为窗口所在的屏幕.

    【讨论】:

    • 感谢您的回复。你有一个中心消息格式的例子吗?我一直在查看类引用,看看我是否能找到可以让窗口居中的调用方法。我明白你所说的 0, 0 的起源我只是不确定中心消息会是什么样子。
    • 没关系,哈哈,我刚通过[窗口中心];它的工作方式和我预期的一样。感谢朋友的帮助。
    【解决方案2】:

    如果没有来自我的“个人框架”中其他地方的各种位和咬的无数依赖项,很难提供以下代码......但我有一个对象类......我猜这类似于苹果在定义一个结构时所做的事情就像NSRect,首先……它提供了一些你想要的便利功能……比如……

    @interface
    NSRect AGPositionRectOnRect(NSRect inner, NSRect outer, NSPoint position);
    // moves the origin of the rect
    NSRect AGCenterRectOnPoint(NSRect rect, NSPoint center);
    // returns the innter rect with its posiion centeredn on the outer rect
    NSRect AGCenterRectOnRect(NSRect inner, NSRect outer);
    // will a square rect with a given center
    NSRect AGSquareAround(NSPoint center, CGFloat distance);
    
    @implementation
    NSRect AGCenterRectOnRect(NSRect inner, NSRect outer) {
        return AGPositionRectOnRect(inner, outer, AGHalfPoint);
    }
    NSRect AGCenterRectOnPoint(NSRect rect, NSPoint center) {
        return NSMakeRect(center.x - rect.size.width  / 2, 
                    center.y - rect.size.height / 2, 
                    rect.size.width, 
                    rect.size.height);
    }
    NSRect AGCenterRectOnRect(NSRect inner, NSRect outer) {
        return AGPositionRectOnRect(inner, outer, AGHalfPoint);
    }
    NSRect AGSquareAround(NSPoint center, CGFloat distance) {
        return NSMakeRect(center.x - distance, 
                    center.y - distance, 
                    2 * distance, 
                    2 * distance
                    );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-28
      • 1970-01-01
      • 1970-01-01
      • 2017-08-11
      相关资源
      最近更新 更多