swift - 在 Cocoa 中保存 CGContext 的路径

标签 swift macos cocoa core-graphics

我正在尝试使用 Cocoa 在 Swift 中为 macOS 编写一个小型绘图应用程序。问题是当再次绘制 NSView 时,最后绘制的线消失了。有没有办法保留绘制的线条?我可以将点保存在数组中,但这会大大降低性能。不幸的是,CGContextSaveGState 函数不保存路径。

这是我正在绘制的 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)
  }
}

最佳答案

对于这种情况,我会退出 CoreGraphics 并使用 NSBezierPath。您可以将其保存在属性中。然后,当更多点进入时,您可以调用 lineToPoint ,然后调用 lines 来绘制它。例如:

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()

关于swift - 在 Cocoa 中保存 CGContext 的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38859766/

相关文章:

xcode - 自定义 UITextView 滚动大小

ios - 使用未声明的类型 'AppDelegate' Swift

git - .gitignore 排除不适用于单个文件

objective-c - NSDocument 应用程序和文件扩展名

swift - NSAttributedString 在初始化时崩溃,但为什么呢?

string - 您如何检查可选字符串的长度?

ruby - 无法在 macos-10.15.6 上 bundle 安装 puma 4.3.5 或 gem puma 与 ruby​​-2.6.6

Mac OS X 10.6.3 下 MySQL 与 PHP 通信问题

objective-c - 如何在 NSCollectionView 中绘制 bezierPath?

objective-c - 使用相对路径将自定义类 .h 文件导入 AppDelegate.h 不起作用