使用getRectsBeingDrawn:使用Swift

时间:2015-09-12 08:37:31

标签: swift cocoa nsview drawrect

我试图在Swift应用中使用NSView来电getRectsBeingDrawn(_:count:),但无法理解如何打开'返回'值 - 方法的签名特别神秘。我通过count变量获得了预期的矩形数,但我不知道如何访问数组中的矩形。 This question解决了同一问题并提出了解决方案,但它并不适用于我 - 我无法访问NSRect结构。

func decideWhatToRedraw() {

    let r1 = CGRect(x: 0, y: 0, width: 10, height: 20)
    let r2 = CGRect(x: 0, y: 100, width: 35, height: 15)

    setNeedsDisplayInRect(r1)
    setNeedsDisplayInRect(r2)
}

override func drawRect(dirtyRect: NSRect) {
    var rects: UnsafeMutablePointer<UnsafePointer<NSRect>> = UnsafeMutablePointer<UnsafePointer<NSRect>>.alloc(1)
    var count: Int = 0
    getRectsBeingDrawn(rects, count: &count)

    // count -> 2
    // But how to get the rects?
}

2 个答案:

答案 0 :(得分:1)

这就是你想要的:

var rects = UnsafePointer<NSRect>()
var count = Int()
getRectsBeingDrawn(&rects, count: &count)

for i in 0 ..< count {

    let rect = rects[i]

    // do things with 'rect' here

}

你创建了两个变量rectscount,并传递了对它们的引用,因此它们充满了信息。

调用getRectsBeingDrawn后,rects指向count个矩形,您可以使用下标来访问这些矩形,就像数组一样。

答案 1 :(得分:0)

swift 3.2

            var rects: UnsafePointer<NSRect>?
            var count = Int()

            getRectsBeingDrawn(&rects, count: &count)
            for i in 0 ..< count {
                let rect = NSIntersectionRect(bounds, rects![i]);
                NSRectFillUsingOperation(rect, NSCompositeSourceOver)
            }