2016-08-09 57 views
2

我想用可可在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) 
    } 
} 

回答

1

對於這種情況,我會走出CoreGraphics中,並使用NSBezierPath。你可以將它保存在一個屬性中。然後您可以撥打lineToPoint作爲更多積分,然後致電stroke來繪製它。例如:

let strokeColor = NSColor(red: red, green: green, blue: blue, alpha: 1.0) 

let path = NSBezierPath() 
path.lineWidth = brushSize 
path.lineCapStyle = .RoundLineCapStyle 
path.lineJoinStyle = .RoundLineJoinStyle 

path.moveToPoint(lastPoint) 
path.lineToPoint(currentPoint) 
... 

strokeColor.setStroke() 
path.stroke() 
1

您正在尋找CGContextCopyPath。它爲您提供了一個CGPath僞對象。最簡單的方法是將其保存爲NSBezierPath作爲其path,因爲NSBezierPath是真實對象,ARC將爲您進行內存管理。