我正在从NSView的drawRect()方法内部对当前的NSGraphicContext进行更改,一切正常。所做的任何更改都将通过随后对drawRect()方法的调用而保持不变。
但是,我想做的是从另一个对象的方法中更改当前上下文。确实是从DrawRect()方法内部调用了此方法。但是这些变化并不是持久的。
代码是这样的:
class SomeView:NSView {
override func drawRect(dirtyRect: NSRect) {
// myAObject is an instance of a Class i create, and stored inside SomeView
// myAObject's exexcuteCode() method, makes changes to the current NSGraphicsContext
myAObjectIntance.executeCode()
// In subsequent calls of drawRect, as the user keeps drawing using the
// mouse, another object, say myBObject's executeCode() method, draws,
// lets say a rectangle.
myBObjectIntance.executeCode()
// Problem is, that any changes done to the current context by myAObjectIntance.executeCode()
// seem to be lost.
// If i change the context and draw inside the same method call, everything is OK.
// If changes and drawing are done by different objects, changes are lost.
}
}
从这两个方法myAObjectIntance.executeCode()和myBObjectIntance.executeCode()中,我使用如下代码获取当前的NSGraphicsContext:
NSGraphicsContext.current!.compositeOperation = .copy
或
NSGraphicsContext.current!.compositeOperation = .clear
我添加了一个更改前景色的小项目。在drawRect()的顺序调用之间,颜色的更改未保留。NSGraphicsContextTest.zip
问题是您期望在对drawRect的多次调用之间保留您的图形和更改;那不会发生。每次调用drawRect时,都会重置上下文状态。那是设计使然。因此,每次调用drawRect时,都需要将上下文的状态设置为所需的状态,然后绘制以填充dirtyRect参数指定的区域。