我想用可可在Swift中爲macOS編寫一個小的繪圖應用程序。問題是,當再次繪製NSView
時,最後繪製的線消失。有沒有辦法保留畫出的線條?我可以將點保存在一個數組中,但這會大大降低性能。不幸的是,CGContextSaveGState
函數不保存路徑。在可可中保存從CGContext的路徑
這裏是我的NSView
我畫的(用鼠標或觸控筆)類:
import Cocoa
class DrawingView: NSView {
// Variables
var lastPoint = CGPoint.zero
var currentPoint = CGPoint.zero
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
var brushSize: CGFloat = 2.0
var dragged = false
// Draw function
override func drawRect(rect: NSRect) {
super.drawRect(rect)
let context = NSGraphicsContext.currentContext()?.CGContext
CGContextMoveToPoint(context, lastPoint.x, lastPoint.y)
if !dragged {
CGContextAddLineToPoint(context, lastPoint.x, lastPoint.y)
} else {
CGContextAddLineToPoint(context, currentPoint.x, currentPoint.y)
lastPoint = currentPoint
}
CGContextSetLineCap(context, .Round)
CGContextSetLineWidth(context, brushSize)
CGContextSetRGBStrokeColor(context, red, green, blue, alpha)
CGContextSetBlendMode(context, .Normal)
CGContextDrawPath(context, .Stroke)
}
// Mouse event functions
override func mouseDown(event: NSEvent) {
dragged = false
lastPoint = event.locationInWindow
self.setNeedsDisplayInRect(self.frame)
}
override func mouseDragged(event: NSEvent) {
dragged = true
currentPoint = event.locationInWindow
self.setNeedsDisplayInRect(self.frame)
}
override func mouseUp(event: NSEvent) {
self.setNeedsDisplayInRect(self.frame)
}
}