我有一个带有一些绘图的自定义NSView:
class ViewController: NSViewController {
@IBOutlet weak var mainView: LineDrawer!
var time = NSTimer()
override func viewDidLoad() {
super.viewDidLoad()
self.view.needsDisplay = true
// Do any additional setup after loading the view.
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
class LineDrawer : NSView {
required init?(coder aDecoder : NSCoder) {
super.init(coder: aDecoder)
}
var lastPt : CGPoint!
var newPt : CGPoint!
var tmp = CGPoint()
override func viewWillDraw() {
super.viewWillDraw()
lastPt = newPt
}
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
self.needsDisplay = true
NSColor.redColor().set()
var newLinear = NSBezierPath()
newLinear.moveToPoint(NSMakePoint(newPt.x, newPt.y))
newLinear.lineToPoint(NSMakePoint(tmp.x, tmp.y))
newLinear.lineWidth = 1
newLinear.stroke()
println(1)
}
override func mouseDown(theEvent: NSEvent) {
super.mouseDown(theEvent)
let location = theEvent.locationInWindow
lastPt = theEvent.locationInWindow
tmp = lastPt
}
override func mouseDragged(theEvent: NSEvent) {
super.mouseDragged(theEvent)
newPt = theEvent.locationInWindow
self.drawRect(self.frame)
tmp = newPt
}
}
它可以工作,但只有在隐藏并使窗口返回后,才会出现线条。我正在寻找在
updateTheView
函数中编写的代码,以便在每次激活mouseDragged时更新视图 最佳答案
您需要将NSBezierstroke
放到drawRect
中,而不是mouseDragged
中。将mouseDragged
中的坐标保存在一个实例数组中,然后使用drawRect
中的Bezier进行最终绘制。drawRect
在视图需要显示时由操作系统调用(无论是从某个地方被needsDisplay = true
告知,还是当窗口被移动时)。在鼠标移动程序中只存储路径。然后当涉及到绘图时drawRect
将实际画出这条线。
class LineDrawer : NSView {
var newLinear = NSBezierPath()
override func drawRect(dirtyRect: NSRect) {
NSColor.redColor().set()
newLinear.lineWidth = 1
newLinear.stroke()
}
override func mouseDown(theEvent: NSEvent) {
super.mouseDown(theEvent)
let location = theEvent.locationInWindow
var lastPt = theEvent.locationInWindow
lastPt.x -= frame.origin.x
lastPt.y -= frame.origin.y
newLinear.moveToPoint(lastPt)
}
override func mouseDragged(theEvent: NSEvent) {
super.mouseDragged(theEvent)
var newPt = theEvent.locationInWindow
newPt.x -= frame.origin.x
newPt.y -= frame.origin.y
newLinear.lineToPoint(newPt)
needsDisplay = true
}
}
我在一个窗户里用一个清晰的视角测试了它。
关于swift - 使用swift功能自动更新NSView,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28239705/